2013-05-01 65 views
0

我是PHP和mySql的新手。我試圖通過使用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

你是什麼意思它看起來像你曾經試圖運行查詢 – 2013-05-01 01:45:41

+0

請不要這樣逃避。使用[bind_param](http://php.net/manual/en/mysqli-stmt.bind-param.php)和[SQL佔位符](http://bobby-tables.com/php)避免嚴重[SQL注入漏洞](http://bobby-tables.com/)。你在哪裏學會這樣做? – tadman 2013-05-01 01:50:12

+0

該查詢正在運行,但它只更新數據庫中的最後一行 – user1754822 2013-05-01 01:52:14

回答

1

幾個問題:

  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'] . "'"; 

    } 
+0

@ user1754822我更新了,我只能在這裏猜出來,直到你回覆評論,但是我認爲你想將這個值設置爲POST數據,並更新'foreach'中的行 - 是嗎? – 2013-05-01 01:56:35

+0

是的。你是對的。 – user1754822 2013-05-01 01:57:19

+0

我試過你的代碼但它不更新任何行.....:( – user1754822 2013-05-01 02:03:32