for循环中准备好的insert语句仅适用于第一次迭代..(PHP)

时间:2012-07-11 18:53:03

标签: php

我想使用以下脚本插入记录数。但是,只有第一个插入。之后,它会停止而不显示任何错误。这些准备好的语句执行有什么问题?

//$dbc = database connection  //shortan here 
// $mid[] = {1,2,3,4};  //sortened here.

$q5 = "INSERT INTO user_book_trn(user_id, member_id, book_id, date_read, lang_id) VALUES (?, ?, ?,  now(), ?)";

$s5 = mysqli_prepare($dbc, $q5);
//Bind the variables:
mysqli_stmt_bind_param($s5, 'iiii', $user_id, $member_id, $book_id, $lang_id);

foreach($mid as $mk => $mv) { //check for each selected check box value from member list:

    $q2 = "SELECT user_id, member_id, book_id FROM user_book_trn WHERE user_id = {$_SESSION['myuser']['userid']} and member_id = {$mv} and book_id= {$w}";

    $r3 = mysqli_query($dbc, $q2);

    if (mysqli_num_rows($r3) == 0) { //title is available for this user.

        //Assign the values to variables:
        $user_id = (int)$_SESSION['myuser']['userid'];
        $member_id = (int)$mv;
        $book_id = (int)$w;
        $lang_id = (int)$_SESSION['lid'];

        //just to check each iteration gets new values:
        echo "user_id : $user_id \n";
        echo "member_id : $member_id \n";
        echo "book_id : $book_id \n";

        //Execute the query:
        mysqli_stmt_execute($s5);
        if (mysqli_affected_rows($dbc) == 1) {
            //this runs ok just for the first iteration.. Why?

            echo "<p><b> The book $t is added. </b></p>";
            $_SESSION['bookid'] = $book_id;
        }
    }
}

1 个答案:

答案 0 :(得分:0)

不知道确切的细节,但据我所知,准备好的语句在执行后绑定到结果集。您需要先重置它

mysqli_stmt_reset($s);

http://php.net/mysqli-stmt.reset

另外,您应该考虑使用有用的变量名称。因为你提到过,你看不到任何错误:

mysqli_stmt_error_list($s5);

http://php.net/mysqli-stmt.error-list

http://php.net/mysqli-stmt.errno

http://php.net/mysqli-stmt.error