Search code examples
phpmysqlsqlarraysget

Passing array in where condition in SQL query using PHP


I am trying to pass an array to a SQL query.

Array contains column names as index they are assigned to their respective values which I got using GET method.

For example I am trying to compile this code:

$a='email';    
$b=array($a => $_GET['x']);    
$sql="SELECT * FROM users WHERE $b";    
echo $sql;

The output that I need is:

SELECT * 
FROM users 
WHERE email='/*value of $_GET['x']*/'

The output that I am getting now however is:

SELECT *  
FROM users 
WHERE Array

Can someone help me? How to make it work?


Solution

  • You need to manipulate the $b array to make it into the string your after, at the moment it's just dumping the content in it's own format.

    This version will do what your after...

    $b=array($a => $_GET['x']);  
    $columns = [];
    foreach ( $b as $name => $value )   {
        $columns[] = "$name = '$value'";
    }
    $sql="SELECT * FROM users WHERE ".implode(" and ", $columns);
    echo $sql.PHP_EOL;
    

    I've made it use and as the condition linking multiple columns, you can change this depending on your requirement.

    This version instead uses bind parameters, the place holder is inserted instead of the value in the query and then you will need to bind the $data array to the prepared statement (how depends in the API your using). This is safer and more flexible (and recommended)...

    $b=array($a => $_GET['x']);
    $columns = [];
    $data = [];
    foreach ( $b as $name => $value )   {
        $columns[] = "$name = ?";
        $data[] = $value;
    }
    $sql="SELECT * FROM users WHERE ".implode(" and ", $columns);
    echo $sql.PHP_EOL;