gpt4 book ai didi

php - PDO - foreach 只更新最后一个

转载 作者:行者123 更新时间:2023-11-30 22:52:37 25 4
gpt4 key购买 nike

我是 PDO 新手,在更新数据库中的数组值时遇到问题。除了更新数组中的多个值外,一切正常。

带有 PHP 代码的 HTML:

<?php  
$next = 0;
echo '<ul>';
$sql = "SELECT * FROM customers LEFT JOIN products ON customers.product_code = products.product_code RIGHT JOIN transactions ON customers.transcode = transactions.transcode WHERE transactions.id = '$id'";

foreach ($pdo->query($sql) as $row) {
echo '<li>'.$row['product_name'] .' x <input name="p_qty['.$next++.']" type="number" value="'. $row['p_quantity'] .'"></li>';
}
echo '</ul>';
?>

输出:

  • MVP 令人难以置信的增重剂(8 磅)x 2
  • MVP 令人难以置信的大量获得者(16 磅)x 2
  • Elite Labs 100% Isoblend(4 磅)x 2

每当我尝试更改第三个结果的数量时,第一和第二个数量也会随之改变。

这是 PDO 代码:

$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "UPDATE transactions JOIN customers ON transactions.transcode = customers.transcode SET transactions.transcode = ?, date = ?, customers.custname = ?, payment = ?, status = ?, customers.p_quantity = ? WHERE transactions.id = ?";
$q = $pdo->prepare($sql);

foreach($_POST['p_qty'] as $qty){
$q->execute(array($transcode, $date, $custname, $payment, $status, $qty, $id));
}
Database::disconnect();
header("Location: index.php");

最佳答案

您的 select 语句正在为相关事务 ID 提取那 3 行。

您的更新语句的 where 子句也仅通过事务 ID 提取,这意味着它将匹配那 3 行。

如果您希望更新语句仅更改其中一种产品的数量,则需要将附加字段传递给 where 子句。

关于php - PDO - foreach 只更新最后一个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27695228/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com