【问题标题】:Insert rows from $_POST when inputs are arrays with PHP PDO当输入是带有 PHP PDO 的数组时,从 $_POST 插入行
【发布时间】:2014-07-29 21:49:35
【问题描述】:

我有一个由 while 循环生成的动态表单,如下所示:

<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>

我正在尝试将每个“响应”和“问题 ID”插入到自己的行中。我相信使用 forloop 来做到这一点是必要的,但无法弄清楚如何访问每个 POST 数组值:

$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();

提交到数据库的值是 response_text 的“Array”。如何访问每一行的实际文本区域值?

【问题讨论】:

  • print_r($_POST); 将向您展示您必须使用的数据结构

标签: php mysql arrays pdo


【解决方案1】:

$_POST['reponse_text'] 是一个数组,像一个数组一样访问它。令牌错误的匹配数是因为您在定义的参数之一上有 if/else 条件。

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
}

请务必将execute() in 放在 foreach 中,否则它将在整个操作之后执行,实际上只插入绑定到查询的最后一个响应文本。

【讨论】:

    【解决方案2】:

    试试这个:

    foreach ($_POST["reponse_text"] as $key => $value) {
    
        $query->bindValue(':user_checkup_id', $user_checkup_id, PDO::PARAM_INT);
    
        if($key == "response_text") {
            $query->bindValue(':response_text', $_POST['reponse_text'][$key], PDO::PARAM_STR);
        } else if($key == "question_id") {
            $query->bindValue(':question_id', $_POST['question_id'][$key], PDO::PARAM_INT);
        }
    }
    

    【讨论】:

    • 试过这个并得到错误:PDOStatement::execute() [pdostatement.execute]: SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens
    猜你喜欢
    • 2014-09-20
    • 1970-01-01
    • 2017-04-21
    • 2012-08-25
    • 2016-02-02
    • 2017-08-27
    • 1970-01-01
    • 2013-10-17
    • 2014-07-16
    相关资源
    最近更新 更多