2013-06-25 94 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