[英]Insert multiple rows in sql via $stmt->bind_param
我想在我的數據庫中插入數組中的多行。
目前,即使我的代碼在數組上循環,它也只插入一行。
這是我的代碼:
$counter = count($the_order);
for($i = 0;$i<$counter;$i++){
list($quantity, $name_prod, $vial_type, $price) = $the_order[$i];
$priceitem = $price/$quantity;
$sql_query = "INSERT INTO tbl_order_items(Prod_name, Vial_type, Prod_price, Prod_qty, Prod_total)
VALUES (?, ?, ?, ?, ?)";
$stmt = $connect->stmt_init();
if($stmt->prepare($sql_query)) {
// Bind your variables to replace the ?s
$stmt->bind_param('sssss',
$name_prod,
$vial_type,
$priceitem,
$quantity,
$price
);
// Execute query
$stmt->execute();
$result = $stmt->affected_rows;
// store result
//$result = $stmt->store_result();
$stmt->close();
}
}
更新后的代碼(print_r):
Array (
[0] => Array ([0] => 5 [1] => Gascure Sirop [2] => [3] => 72.5 RON )
[1] => Array ( [0] => 5 [1] => Graviola Star [2] => 100 Tablete [3] => 277.5 RON )
[2] => Array ( [0] => 1 [1] => Graviola Star [2] => 100 Tablete [3] => 0.0 RON ) )
首先,您應該記住,使用准備好的語句的主要好處之一是您可以准備一次語句並多次執行它。 每次改變參數的值。 這加快了速度,因為數據庫只需要編譯和優化一次查詢。 所以將准備移到循環之外
其次,如果您想一次性進行許多數據庫更改,那么圍繞這些事情進行的事務是一個很好的主意,因此如果中間出現問題,您將獲得所有 INSERT/UPDATE 或一個都沒有,因此您不會離開您的數據庫處於無意義狀態。
最后,在測試時這是一個好主意,特別是如果您在實時服務器上進行開發,其中可能會抑制錯誤以將錯誤報告設置為 On,以便您在瀏覽器上看到任何錯誤。 但是請記住在測試腳本后將其刪除,您不希望用戶看到有關任何錯誤的這么多信息,因為它只會幫助黑客。
ini_set('display_errors', 1);
ini_set('log_errors',1);
error_reporting(E_ALL);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$sql = "INSERT INTO tbl_order_items
(Prod_name, Vial_type, Prod_price, Prod_qty, Prod_total)
VALUES (?, ?, ?, ?, ?)";
$stmt = $connect->prepare($sql);
if ( !$stmt) {
// report error and exit, you can do this
exit;
}
// begin Transaction
$connect->begin_transaction();
$counter = count($the_order);
for($i = 0;$i<$counter;$i++){
list($quantity, $name_prod, $vial_type, $price) = $the_order[$i];
$priceitem = $price/$quantity;
$stmt->bind_param('sssss',
$name_prod,
$vial_type,
$priceitem,
$quantity,
$price);
// Execute query
$res = $stmt->execute();
if ( !$res ) {
echo $connect->error;
$connect->rollback();
exit;
}
$result = $stmt->affected_rows;
}
$connect->commit();
最后,您可能想檢查列的數據類型。 您正在使用'sssss'
,因此將所有內容都視為文本,但可能例如quantity
和price
以及price
priceitem
可能不是文本。
但是如果至少設置了錯誤報告,您應該看到與數據類型相關的錯誤。
我還注意到您的price
字段包含RON
,一種貨幣代碼。 最好不要把它放在price
字段中。 如果您網站上的所有內容都在 RON 中,則不需要,如果不是所有內容都在 RON 中,那么我建議在表中使用單獨的列來保存該信息。 然后您的價格字段可以更改為數字,這將允許您在 SQL 中進行簡單的計算,因為它使用 char 數據類型意味着您不能做簡單的算術,因為RON
意味着列類型必須是某種類型的 char
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.