-1
我有一些代碼來更新php mysql中的多行像這樣。如何在php中更新多行mysql mysql
<?php
$idOrder = $_GET['idOrder'];
$conn = new MySQLi('localhost','root','','project_ecommerce');
$query_select = "SELECT status FROM order_product WHERE id_order='".$idOrder."'";
$sql_select = $conn->query($query_select);
$result_select = $sql_select->fetch_assoc();
$status ='';
if ($result_select['status'] == 0) {
$status .= 1;
}else{
$status .= 0;
}
$query_update = "UPDATE order_product SET status='".$status."' WHERE id_order='".$idOrder."'";
$sql_update = $conn->query($query_update);
if ($sql_update == TRUE) {
$query_select_product = "SELECT order_product.id_product AS ID_PRD, order_product.status AS STATUS, order_product.qty AS QTY_ORD, products.stock AS STOCK FROM order_product JOIN products ON order_product.id_product = products.id_product WHERE order_product.id_order ='".$idOrder."'";
$sql = $conn->query($query_select_product);
$result = $sql->fetch_all(MYSQLI_ASSOC);
$stock_update='';
for ($i=0; $i < count($result); $i++) {
if ($result[$i]['STATUS'] == 0) {
$stock_update .= ($result[$i]['STOCK']+$result[$i]['QTY_ORD']);
}else{
$stock_update .= ($result[$i]['STOCK']-$result[$i]['QTY_ORD']);
}
$update_product = "UPDATE products SET stock='".$stock_update."' WHERE id_product='".$result[$i]['ID_PRD']."'";
$sql_update_product = $conn->query($update_product);
}
}
echo $idOrder;
?>
如果status
更新爲1
我給結果是這樣的:
+----------------+-------+
| id_product | stock |
+----------------+-------+
| PRD-0416-17-1 | 100 |
| PRD-0416-17-10 | 100 |
| PRD-0416-17-11 | 98 |
| PRD-0416-17-12 | 9898 |
+----------------+-------+
如果status
更新爲0
我給結果是這樣的:
+----------------+---------+
| id_product | stock |
+----------------+---------+
| PRD-0416-17-1 | 100 |
| PRD-0416-17-10 | 100 |
| PRD-0416-17-11 | 100 |
| PRD-0416-17-12 | 1009900 |
+----------------+---------+
我怎樣才能解決這個問題?
您的代碼很容易受到[** SQL注入攻擊**](https://en.wikipedia.org/wiki:
這整個事情可以在一個單一的查詢來完成/ SQL_injection)。你應該使用[** mysqli **](https://secure.php.net/manual/en/mysqli.prepare.php)或[** PDO **](https://secure.php.net/ manual/en/pdo.prepared-statements.php)準備帶有綁定參數的語句,如[**這篇文章**]所述(https://stackoverflow.com/questions/60174/how-can-i-prevent-sql步噴射功能於PHP)。 –
您在分配中使用'。=',因此您將一行中的值連接到前一行中的值。 – Barmar
@AlexHowansky感謝您的建議 –