简体   繁体   中英

PHP passing an array into a SQL query

I create an array from checkboxes that are "checked" via JS.

Simple Checkboxes:

     <div class="checkbox">
          <label>
            <input type="checkbox" name="checkSearch[]" value="One" checked /> One
          </label>
      </div>
      <div class="checkbox">
          <label>
            <input type="checkbox" name="checkSearch[]" value="Two" checked /> Two
          </label>
      </div>
      <div class="checkbox">
          <label>
            <input type="checkbox" name="checkSearch[]" value="Three" checked /> Three
          </label>
      </div>

JS:

        var selectedItems = [];
        $('input[type="checkbox"]:checked').each(function () {
                selectedItems .push($(this).val());
        });

        //passing array in a function
        searchLocations(pass1, pass2, selectedItems);

At this point what is outputted is (assuming all three checkboxes are "checked"):

["One", "Two", "Three"];

Here's where I'm not quite sure what needs to happen next?

Can I include the array as a URL string and use the PHP .implode function later on within my SQL statement?

Here's what I've tried:

function searchLocations(pass1, pass2, selectedItems) {
var searchUrl = 'searchLocations.php?pass1=' + pass1 + '&pass2=' + pass2 + '&selectedItems=' + selectedItems;
...
}

searchLocations.php

$pass1 = $_GET['pass1'];
$pass2 = $_GET['pass2'];
$selectedItems = $_GET['selectedItems'];
$selectedItems = "  '".implode("', '", $selectedItems)."'  ";

$query = sprintf("SELECT * FROM dbtable WHERE pass1 = $pass1 AND pass2 = $pass2 AND selectedItems IN ($selectedItems)");

$selectedItems needs to read like this in the SQL query: IN ('One', 'Two', 'Three')..

Define a function that implodes and allows you to wrap elements:

function implode_wrapped($before, $after, $glue, $array) 
{
    $out = '';
    foreach ( $array as $item ){
        $out .= $before.$item.$after.$glue;
    }

    return substr($out, 0, -strlen($glue));
}

You can then do stuff like....

Implode the array values and append to your query string:

implode_wrapped('selectedItems[]=', '', '&amp;', $items);

Note that I'm using 'selectedItems[]'. Your code - function searchLocations() - in its current form is not sending selectedItems as an array.

Implode and use with SQL:

implode_wrapped("'", "'", ',', $items);

Note that you need to sanitize any values that get sent to SQL or you will be hacked.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM