0

I need to update an array into mysql table.

this is my array

[cat2] => Array
                (
                    [0] => 34
                    [1] => 48
                    [2] => 49
                    [3] => 46
                )

and I want my output as 34,48,49,46 to move into a table called shops and column called category. This is code I written, $shop['cat2'] contains the array i posted above. Please help me. This code is keep only 34 in all fields of column category

foreach ($shop['cat2'] as $k => $v) {
    $query = "UPDATE shops SET categories2=$v";
    mysql_query($query);
    }
4

2 回答 2

0

查看内函数:implode(",", $shop['cat2'])

您可能还想查看Foreign Keys。使用外键时,您可以使用joinSQL 语句从多个列中检索数据。将类别存储为一个字段时,例如在您的示例中,这是不可能的。

为此,您需要一个新表:ShopCategory使用 columns:ShopID和,这些列将分别与您的和表CategoryID具有外键关系。ShopCategory

正如 Michael Berkowski 在评论中已经指出的那样,如果您不使用where子句,则此 SQL 语句将更新您所有商店的类别!

$query = "UPDATE shops SET categories2='".implode(",", $shop['cat2'])."' WHERE id=".$shop;

于 2012-10-15T14:56:34.413 回答
0

为了将这些数组元素中的每一个应用于列的一行,category您需要首先从表中获取唯一的 id ,然后在更新查询的子句shops中使用该唯一标识符值循环遍历它:WHERE

我们将在循环mysql_fetch_assoc()内部调用foreach()每个数组元素拉一行。这假设您有一列shops.id是每个商店的唯一标识符。

// If `id` is not the unique id per shop, substitute the correct column
$rowids = mysql_query("SELECT id FROM shops ORDER BY id");
if  ($rowids) {
  // Loop over your array, and do one update per array elem
  foreach ($cat2 as $cat) {
     $row = mysql_fetch_assoc($rowids);
     $id = row['id'];
     // Your values are ints, so no need to quote and escape.
     // If you do use other string values, be sure to mysql_real_escape_string() them and single-quote
     $upd = mysql_query("UPDATE shops SET category = $cat WHERE id = $id");
     // Report error on this iteration
     if (!$upd)  {
        echo "error updating $id" . mysql_error();
     }
  }
}
else {
   echo "Couldn't get row ids. " . mysql_error(); 
}
于 2012-10-15T15:02:55.573 回答