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 fx2n系列plc的自控成型机模拟
  • ¥15 时间序列LSTM模型归回预测代码问题
  • ¥50 使用CUDA如何高效的做并行化处理,是否可以多个分段同时进行匹配计算处理?目前数据传输速度有些慢,如何提高速度,使用gdrcopy是否可行?请给出具体意见。
  • ¥15 基于STM32,电机驱动模块为L298N,四路运放电磁传感器,三轮智能小车电磁组电磁循迹(两个电机,一个万向轮),如何通过环岛的原理及完整代码
  • ¥20 机器学习或深度学习问题?困扰了我一个世纪,晚来天欲雪,能饮一杯无?
  • ¥15 c语言数据结构高铁订票系统
  • ¥15 关于wkernell.PDB加载的问题,如何解决?(语言-c#|开发工具-vscode)
  • ¥100 某宝多次访问被拒绝,求解
  • ¥15 (标签-STM32|关键词-智能小车)
  • ¥20 关于#stm32#的问题,请各位专家解答!