php binding dynamic number of variables for batch insert query

我是研究僧i 提交于 2019-12-02 03:52:34

问题


I have a web service where a user passes up a dynamic number of questions.

On the php side I am using explode with the ? to strip out each question. I then need to do a batch insert.

What I've done so far is as follows:

$checkInQs = explode("?", trim($_POST['checkInQs'], "?"));
    $checkInSql = "INSERT INTO CheckListQs (ID, GeofenceID, type, question) VALUES ";
    $checkInInsertQuery = array();
    $checkInInsertData = array();
    foreach($checkInQs as $q){
         $checkInInsertQuery[] = "('',?, 1, ?)";
         $checkInData[] = $geofenceID;
         $checkInData[] = $q;
    }

Based on another similar example, the following would be how to finish it off with pdo:

if (!empty($checkInInsertQuery)) {
        $checkInSql .= implode(', ', $checkInInsertQuery);
        $stmt = $db->prepare($checkInSql);
        $stmt->execute($checkInData);
    }

I'm not really sure how to bind the parameters in my case. I'm using procedural binding. I would usually bind parameters like so:

mysqli_stmt_bind_param($stmt, "is", $geofenceID, $question);
mysqli_stmt_execute($stmt);

I think the type part is as simple as:

$bindVar = '';

for ($i = 0; $i < count($checkInQs); $i++){
    $bindVar .= "is";
}

But not I'm not sure how to manage passing in the rest of the data?


回答1:


In the end, I chose to make use of transactions, commits and rollbacks to get my desired outcome:

mysqli_query($con, "start transaction;");

$allQueriesOK = true;
$checkInQs = explode("?", trim($_POST['checkInQs'], "?"));
$checkInSql = "INSERT INTO CheckListQuestions (ID, GeofenceID, type, question) VALUES ('',?,0,?)";
mysqli_stmt_prepare($stmt, $checkInSql);

foreach ($checkInQs as $q) {            
    mysqli_stmt_bind_param($stmt, "is", $geofenceID, $q);
        if (!mysqli_stmt_execute($stmt)){
            $allQueriesOK = false;
            $message = mysqli_error($con);
            break;
        }
    }

    mysqli_stmt_close($stmt);

    if ($allQueriesOK){
        mysqli_query($con, "commit;");
    }
    else{
        mysqli_rollback($con);
    }       


来源:https://stackoverflow.com/questions/34989107/php-binding-dynamic-number-of-variables-for-batch-insert-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!