2012-10-15 31 views
0

我需要将数组更新到mysql表中。将数组更新到mysql表中

这是我的数组

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

,我想我作为34,48,49,46输出移动到名为类的表称为商店和列。这是我写的代码,$ shop ['cat2']包含我上面发布的数组。请帮帮我。此代码是只有34不断在列类别的所有领域

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

你是什么意思**移动到表**中? – hjpotter92

+3

您需要一个'WHERE'子句来只更新一行。这也意味着你需要从'商店'中取出id或'WHERE'子句中使用的东西。 –

+0

我想34,48,49,46移动到列“类别”,表“商店”的第一个领域 – user1694724

回答

0

为每个数组元素应用到你的category列一行,则需要首先从shops表中提取唯一的ID,并遍历它,使用唯一标识符值在更新查询的WHERE子句中:

我们将在foreach()循环内调用mysql_fetch_assoc()来为每个数组元素拉一行。假设您有一列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(); 
} 
0

查找到implode功能:implode(",", $shop['cat2'])

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

您需要为一个新表:ShopCategory与列:ShopIDCategoryID,这些列将分别有一个外键关系到你的ShopCategory表。

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

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

+0

我希望34,48,49,46移到列“类别”,表格“商店”的第一个字段中 – user1694724