我是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'";
}
答案 0 :(得分:1)
有几个问题:
$id
声明两次。$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
设置为从第一个查询返回的值:< / p>
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'] . "'";
}