Search code examples
phpsqlclause

PHP array for an SQL “IN” clause?


i am trying to search multiple roll numbers from database with html form e.g 2345,7654,8976 in a single field now for php i am trying

$query = "SELECT `firstname`, `lastname`, `roll`, `board`, `city` FROM `result` WHERE 1=1";

if(isset($_POST['mroll']))
{
$mroll=$_POST['mroll'];
$query.="and roll IN ('$mroll')";
}

but $_POST['mroll'] will be like this => 2345,7654,8976 for sql i have to quote them like this => '2345','7654','8976' before using it in query please help.


Solution

  • Since the values are integers if you unquote the variable the query will be valid. This will open you to SQL injections though. You should use a parameterized query and pass each value in as a placeholder. Try something like:

    $query = "SELECT `firstname`, `lastname`, `roll`, `board`, `city` FROM `result` WHERE 1=1";
    if(isset($_POST['mroll'])) {
         $mroll=$_POST['mroll'];
         foreach(explode(',', $mroll) as $int) {
             $placeholders .= '?, ';
             $params[] = $int; 
         }
         $placeholders = rtrim ($placeholders, ', ');
         $query .= " and roll IN ($placeholders)";
    }
    

    Demo: https://eval.in/657610

    Technically you could just change:

    $query.="and roll IN ('$mroll')";
    

    to

    $query.="and roll IN ($mroll)";
    

    highly discourage that approach though.

    Your query when quoted becomes:

    SELECT `firstname`, `lastname`, `roll`, `board`, `city` FROM `result` WHERE 1=1and IN ('2345,7654,8976')
    

    which makes 2345,7654,8976 one value, not three values.