簡體   English   中英

通過MySQL / PHP中的foreach循環進行更新查詢

[英]UPDATE query through foreach loop in mysql/php

我確實有一個像這樣的數組:

[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)

這個腳本會有什么問題? 希望有人可以幫助我。

謝謝。

您需要在循環中綁定參數:

// 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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM