Search code examples
arrayssimplecart

Using array for MySQL Select Statement


Apologies in advance if i use the wrong definition of a word...I am using SimpleCart to pass $.Post variables to a PHP page. If i print the array i get

Array ( [currency] => CAD [shipping] => 0 [tax] => 1.69 [taxRate] => 0.13 [itemCount] => 3 [item_name_1] => Dinner Plate [item_quantity_1] => 1 [item_price_1] => 5 [item_options_1] => code: 110 [item_name_2] => Side Plate [item_quantity_2] => 1 [item_price_2] => 4 [item_options_2] => code: 125 [item_name_3] => Mixing Bowl [item_quantity_3] => 1 [item_price_3] => 4 [item_options_3] => code: 66 )

What I am struggling with (and going around in circles) is a method to do the following..

Explode the [item_options] variable to strip out the CODE: part of the value and just leave the numeric section.

concatenate these values into a string so i can use a SELECT statement to only pull records that have an ID passed in the [item.options].

I understand how to explode a single parameter, but cannot work out how to loop through the array, explode the key and create the value i need for the SQL.

Any help or pointers to relevant tutorials would be much appreciated


Solution

  • $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