2013-06-25 68 views
0

如果我使用錯誤的單詞定義,我會提前道歉......我正在使用SimpleCart將$ .Post變量傳遞給PHP頁面。如果我打印陣列我得到對MySQL使用數組Select語句

Array([currency] => CAD [shipping] => 0 [tax] => 1.69 [taxRate] => 0.13 [itemCount] => 3 [item_name_1] => [item_quantity_1] => 1 [item_price_1] => 5 [item_options_1] => code:110 [item_name_2] =>副牌[item_quantity_2] => 1 [item_price_2] => 4 [item_options_2] => code:125 [item_name_3] =>混合碗[item_quantity_3] => 1 [item_price_3] => 4 [item_options_3] =>代碼:66

我所掙扎(和在兜圈子)是這樣的方法做下列事情..

分解[item_options]變量以去掉CODE:值的一部分,只留下數字部分。

將這些值連接成一個字符串,所以我可以使用一個SELECT語句來只提取具有在[item.options]中傳遞的ID的記錄。

我明白如何爆炸一個參數,但不能解決如何遍歷數組,爆炸鍵和創建我需要的SQL值。

任何幫助或指針相關教程,將不勝感激

回答

0
$codes = array(); 
foreach ($_POST as $key => $value) { // Loop through the $_POST array 
    if (preg_match('/^item_options_/', $key)) { // And validate the value 
    $item_arr = explode(' ', $value); 
    $item_id = $item_arr[1]; // Get the ID number from the value 
    if (is_numeric($item_id)) { // Validate it 
     $codes[] = $item_id; // Add it to the array we're building 
    } 
    } 
} 
$codes_string = implode(', ', $codes); // Concatenate them into a string that can be used in a SQL IN clause 

$sql = "SELECT * from table WHERE id IN ($codes_string)"; // Build the SQL 
+0

謝謝Barmar!但似乎是在這一行中有語法錯誤? $ item_id = explode('',$ value)[1]; //從值中獲取ID號碼 – user2480507

+0

修復它。您不能將下標應用於函數調用。 – Barmar

+0

感謝您花時間幫助陌生人,我真的很感激 – user2480507