About using IN in mysql query

Hello,

If the searched text is not working
is it not possible to search e-mails?
$array = array("[email protected]", "[email protected]", "[email protected]");

$sql = (" SELECT * FROM table WHERE  user_mail IN(".implode(',',$array).") ");

No problem here, because the wanted numerical
$array = array("1", "2", "3");

$sql = (" SELECT * FROM table WHERE user_id IN(".implode(',',$array).") ");

A. Don’t put external, unknown, dynamic values directly into an sql query statement. Use a prepared query instead.
B. Email addresses are strings and if put into an sql query statement would need to be surrounded by single-quotes. Your error handling for the sql query should be returning an sql error. Using a prepared query would avoid this problem, since you only put a ? place-holder in the sql query statement for each value, regardless of what data type the value actually is.
C. Those are numbers in your 2nd example and can be put into an sql query statement as is.
D. When you switch to use a prepared query, use FIND_IN_SET() instead of an IN() comparison, since you can supply the 2nd parameter to find_in_set() via a single prepared query place-holder. Using an IN() comparison requires a separate prepared query place-holder for each value.

How to enclose the array in single quotes?

Don’t. Use a prepared query.

Assuming PDO

// find_in_set expects a parameter in csv
$emails = implode(',', $array);

$sth = $dbh->prepare('SELECT * FROM table WHERE FIND_IN_SET(user_id, ?)');
$sth->execute([$emails]);
$users = $sth->fetchAll();

Thank you very much for your help
But I am using Mysqli not PDO

To solve this problem
while () instead of foreach () I solved using

   $array = array("[email protected]", "[email protected]", "[email protected]");
        foreach ($array AS $key => $value){
        
        $sql = (" SELECT * FROM table WHERE user_mail IN('".$value."') ");
        
        }

You should use prepared queries, mysqli supports them as well. You seem to be running one query for each email so you don’t really use IN.

Yes, I loop for each mail
How do I use the code while() you give an example?
I’m newbie

$emails = implode(',', $array);

$sth = $dbh->prepare('SELECT * FROM table WHERE FIND_IN_SET(user_id, ?)');
$sth->execute([$emails]);
while ( $users = $sth->fetchAll() ) {

}

Warning: mysqli_stmt::execute() expects exactly 0 parameters, 1 given in
Fatal error: Uncaught Error: Call to undefined method mysqli_stmt::fetchAll() in
Error: Call to undefined method mysqli_stmt::fetchAll() in

Sponsor our Newsletter | Privacy Policy | Terms of Service