gpt4 book ai didi

php - 使用 PHP 和 MySQL 更新多行

转载 作者:行者123 更新时间:2023-11-29 13:53:25 27 4
gpt4 key购买 nike

我是 php 和 mySql 的新手。我正在尝试使用 php 和 mysql 更新多行。

我在更新 MySQL 数据库中的多行时遇到问题。它仅更新数据库中表的最后一行。例如,用户单击查看产品。该页面将列出数据库中当前的 10 个产品。用户希望通过点击的方式更新产品信息。更新完成后,用户点击提交。

问题是它只捕获和更新表中最后一个产品的信息。我尝试将其放入 foreach() 函数中。但这不起作用。

请帮忙。我刚学PHP和mySQL不到一周。我非常感谢任何帮助。

<?php
include 'dbconn.inc.php';
include 'functions.inc.php';

$sql = "SELECT * FROM products";
$res = $mysqli->query($sql);

while( $row = $res->fetch_array(MYSQLI_ASSOC) ){
$products($row['id']) = 'id';
}

$id = $mysqli->real_escape_string( $_POST['id'] );
$weight = $mysqli->real_escape_string( $_POST['weight'] );
$name = $mysqli->real_escape_string( $_POST['name'] );
$supplier_id = $mysqli->real_escape_string( $_POST['supplier_id'] );
$price = $mysqli->real_escape_string( $_POST['price'] );
$description = $mysqli->real_escape_string( $_POST['description'] );

foreach( $products as $id){
$sql = "UPDATE products
SET
`id` = '$id',
`weight` = '$weight',
`price` = '$price',
`name` = '$name',
`supplier_id` = '$supplier_id',
`description` = '$description'

WHERE `id` = '$id'";

}

最佳答案

几个问题:

  1. 首先,您声明变量 $id 两次。
  2. 您应该在循环中使用 $key 而不是 $value

相反,试试这个:

foreach( $products as $key => $value){
$sql = "UPDATE products
SET
`id` = '$id',
`weight` = '$weight',
`price` = '$price',
`name` = '$name',
`supplier_id` = '$supplier_id',
`description` = '$description'

WHERE `id` = '$key'";

}

使用数组key而不是它的value的原因是因为在下面的行中您将数组的key设置为第一个查询返回的值:

while( $row = $res->fetch_array(MYSQLI_ASSOC) ){
$products($row['id']) = 'id';
}

我可能建议这样做:

$products = array();

while( $row = $res->fetch_array(MYSQLI_ASSOC) ){
$products[]['id'] = $id;
}

foreach( $products as $product){
$sql = "UPDATE products
SET
`id` = '$id',
`weight` = '$weight',
`price` = '$price',
`name` = '$name',
`supplier_id` = '$supplier_id',
`description` = '$description'

WHERE `id` = '" . $product['id'] . "'";

}

关于php - 使用 PHP 和 MySQL 更新多行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16311564/

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