dongqun5769 2014-07-29 21:49
浏览 70
已采纳

当输入是带有PHP PDO的数组时,从$ _POST插入行

I have a dynamic form generated by a while loop that looks like this:

<form>
<?php while ($questions = $query->fetch(PDO::FETCH_ASSOC)) { ?>
<textarea name="reponse_text[]"></textarea>
<input type="hidden" name="question_id[]" value="<?php echo $questions['question_id']; ?>">
<?php } ?>
</form>

I am trying to insert each 'response' and 'question_id' into its own row. I believe using a forloop to do this is necessary but can't figure out how to access each POST array value:

$user_checkup_id = $db->lastInsertId();

$query = $db->prepare("INSERT INTO user_responses (user_response_text, question_id, user_checkup_id) 
VALUES (:user_response_text, :question_id, :user_checkup_id)");

foreach ($_POST as $key => $value) {

    $query->bindValue(':user_checkup_id', $user_checkup_id, PDO::PARAM_INT);

    if($key == "response_text") {
        $query->bindValue(':response_text', $value, PDO::PARAM_STR);
    } else if($key == "question_id") {
        $query->bindValue(':question_id', $value, PDO::PARAM_INT);
    }
}

$query->execute();

The value submitting to the database is "Array" for response_text. How do I access the actually text area value for each row?

  • 写回答

2条回答 默认 最新

  • dplase3140 2014-07-30 03:12
    关注

    $_POST['reponse_text'] is an array, access it like one. The match number of token error is because you have an if/else condition on one of the parameter being defined.

    foreach ($_POST['reponse_text'] as $i => $value) {
    
        $query->bindValue(':user_checkup_id', $user_checkup_id, PDO::PARAM_INT);
    
        $query->bindValue(':response_text', $value, PDO::PARAM_STR);
        $query->bindValue(':question_id', $_POST['question_id'][$i], PDO::PARAM_INT);
        // here you do them at once or the other parameter won't be defined
    
        $query->execute(); // then you execute, for each different response text
    }
    

    be sure to put the execute() in the foreach or it will get executed after the whole thing, effectively only inserting the last response text having been bound to the query.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 路易威登官网 里边的参数逆向
  • ¥15 Arduino无法同时连接多个hx711模块,如何解决?
  • ¥50 需求一个up主付费课程
  • ¥20 模型在y分布之外的数据上预测能力不好如何解决
  • ¥15 processing提取音乐节奏
  • ¥15 gg加速器加速游戏时,提示不是x86架构
  • ¥15 python按要求编写程序
  • ¥15 Python输入字符串转化为列表排序具体见图,严格按照输入
  • ¥20 XP系统在重新启动后进不去桌面,一直黑屏。
  • ¥15 opencv图像处理,需要四个处理结果图