通过mysql / php中的foreach循环进行UPDATE查询

时间:2015-07-21 16:25:47

标签: php mysql

我有一个像这样的数组:

[cuisines] => Array
    (
        [0] => 17
        [1] => 20
        [2] => 23
        [3] => 26
    )

现在我需要用这些值更新mysql表。所有值都属于一个用户。

所以我尝试了这样:

if (isset($_POST['cuisines'])) {    
    $cuisines = $_POST['cuisines'];         
} else {
    $error_alert[] = "Please select at least one cuisine";
}   

if (empty($error_alert)) { // If everything's OK... 

    // Make the update query:
    $sql = 'UPDATE restaurant_cuisines 
                        SET restaurant_id = ?
                            , cuisine_id = ?  
                    WHERE restaurant_id = ?'; 

    $stmt = $mysqli->prepare($sql);
    // Bind the variables:
    $stmt->bind_param('iii', $restaurant_id, $cuisine_id, $restaurant_id);

    foreach ($cuisines as $value) {
        $cuisine_id = $value;
        // Execute the query:
        $stmt->execute();       
    }   

    // Print a message based upon the result:
    if ($stmt->affected_rows >= 1) {
        echo 'updated';

    } 
    // Close the statement:
    $stmt->close();
    unset($stmt);
}

但是这个查询没有正确更新mysql。这就是我运行这个脚本的原因。

mysql> select * from restaurant_cuisines where restaurant_id = 4;
+---------------+------------+
| restaurant_id | cuisine_id |
+---------------+------------+
|             4 |         26 |
|             4 |         26 |
|             4 |         26 |
+---------------+------------+
3 rows in set (0.00 sec)

这个脚本会出现什么问题? 希望有人可以帮助我。

谢谢。

1 个答案:

答案 0 :(得分:2)

您需要在循环中绑定参数:

// Delete old entries:
$sqlDelete = 'DELETE FROM restaurant_cuisines WHERE restaurant_id = ?'; 
$stmtDelete = $mysqli->prepare($sqlDelete);
$stmtDelete->bind_param($restaurant_id);
$stmtDelete->execute(); 
$stmtDelete->close();
unset($stmtDelete);  

// now prepare to insert new values
$sqlInsert = 'INSERT INTO restaurant_cuisines (restaurant_id,cuisine_id) 
              VALUES (?,?)'; 
$stmtInsert = $mysqli->prepare($sqlInsert);

foreach ($cuisines as $value) {

    // Bind the variables:
    $stmtInsert->bind_param($restaurant_id, $value);

    // Execute the query:
    $stmtInsert->execute();    

    // Print a message based upon the result:
    if ($stmtInsert->affected_rows >= 1) {
        echo 'updated';
    }   
}   
// Close the statement:
$stmtInsert->close();
unset($stmtInsert);