循环遍历PHP数组并应用SQL

时间:2014-05-05 18:00:40

标签: php sql arrays

我有一个数组,我希望循环并在记录存在时应用一些SQL。 我有类似的东西:

$discontinuedProducts = ["MTUC7000AWS","MTUC7000AWB"];
$updateDiscontinuedProductsToInactive = mysql_query("UPDATE 'table_name' SET 'available_for_order' = 0 WHERE 'product_id' = $discontinuedProducts  ");

但我认为我的代码甚至没有执行,他们只是被宣布。

1 个答案:

答案 0 :(得分:0)

您的sql语句不可能正常工作,因为您连接的变量$ discontinuedProducts不是字符串而是数组。您需要像这样修改代码

// make string from the array
foreach($discontinuedProducts as $discontinuedProduct)
{
      // put single quotes around productname, comma at end and add to string
      $whereinstring .= "'$discontinuedProduct',";
}

// remove trailing comma
$whereinstring = trim($whereinstring,',');

// the sql
$sql = "UPDATE 'table_name' 
        SET 'available_for_order' = 0 
        WHERE 'product_id' IN ( $whereinstring ) ";

// and use this sql string in the mysqlfunction of your choice ....