簡體   English   中英

使用php使用准備好的語句插入多個值時出錯

[英]Error inserting multiple values with prepared statement using php

當我嘗試使用預處理語句將多個值插入mysql數據庫時出現錯誤。

我不斷收到這個錯誤

Warning: mysqli_stmt::bind_param(): Number of elements in type definition string doesn't match number of bind variables.

我認為將$ data視為一個單一值,我現在不知道該怎么辦

   $keys = (?, ?, ?);
   $types = "iii";
   $data = "1, 3, 500";
   if ($stmt2 = $conn->prepare("INSERT INTO tranx (user, type, amount) VALUES (?, ?, ?),$keys")) {
   $ortype = 1;     
   $stmt2->bind_param("iii".$types, $userid, $ortype, $amount, $data);
   $stmt2->execute();
   $stmt2->close();

   } 

您正在嘗試與變量綁定,但需要手動分配它們。 除此之外,您的參數數量不匹配。

您有3個占位符,3個類型定義和4個值。 它們是一對一的關系,所以類型定義的數量(您的iii )需要與占位符的數量匹配? 以及綁定的值數(按占位符順序)。

// $keys = (?, ?, ?); // Removed this, syntax error and you bind it manually anyway later
// $types = "iii"; // You bind it manually later
$data = "1, 3, 500";

// Removed ',$keys' from your query, you manually put the placeholders
if ($stmt2 = $conn->prepare("INSERT INTO tranx (user, type, amount) VALUES (?, ?, ?)")) {
    $ortype = 1;

    // removed '.$types' - you bind it manually
    // Also removed $data - you have 3 values, 3 columns, not 4
    $stmt2->bind_param("iii", $userid, $ortype, $amount);
    $stmt2->execute();
    $stmt2->close();
}

是的,您的$data是單個值,而不是參數列表。

該文檔也包含很好的示例。

參考文獻

試試這個邏輯,看看是否可行:)

$data = array(array(1,3,5), array(2,4,6));
$sql = 'INSERT INTO tranx (user, type, amount) VALUES (?, ?, ?)';

if($stmt = $conn->prepare($sql)){

$stmt->bind_param("iii", $usr, $type, $amt);

foreach ($data as $v) {

$usr = $v[0];
$type = $v[1];
$amt = $v[2];

$stmt->execute();

if($stmt->insert_id <= 0){
trigger_error('Insert fail. Error: ' . $stmt->error);
break;
}
}
$stmt->close();
$conn->close();
}
else{
trigger_error('Prepare fail.');
}

我認為$ data是一個單一值

當然是。 如果無論如何它都是一個單一的值,為什么會否則呢?

我現在不知道該怎么辦

好吧,您能做的最好的事情就是問一個問題。 您不是在這里問這個問題,而是一個真正的問題,解釋您要做什么以及為什么做。 由於沒有這樣的問題,我們只能猜測您需要執行多次插入,但是需要采取一些特殊的方法。

要做到這一點,創建一個包含所有數據的單個陣列。

$data = [];
$data[] = $userid;
$data[] = $ortype;
$data[] = $amount;
$data[] = 1;
$data[] = 3;
$data[] = 500;
$count = count($data);

然后用占位符創建一個字符串

$values = implode(',', array_fill(0,  $count, '(?, ?, ?)'));

然后用類型創建一個字符串

$types = str_repeat("iii", $count);

最后創建查詢並執行它

$stmt = $conn->prepare("INSERT INTO tranx (user, type, amount) VALUES $values");
$stmt->bind_param($types, ...$data);
$stmt->execute();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM