Hello to all,
I am trying to execute a mysql query for selecting * rows from the table where user name = [one of the usernames stored in an array].

Ok. Sorry if I am not clear.
Now I have an array naming $users[].
I want to select all the users listed in $users[] from a mysql table.
Please tell me how can I do that.

$query="SELECT * FROM users WHERE ";
foreach($users as $name)
$query="SELECT * FROM users WHERE name='$name'";
//Push the rows you have found to the foundRows array declared above


Hope it gives you an idea. But I think this solution will be ineffiecient if the array has so many users e.g 10,000

You can also do this in a single query, instead of looping to make multiple queries. Just implode


// glue them together with ', '
$userStr = implode("', '", $users);

$query="SELECT * FROM users WHERE name in ('$userStr')";

With the 'glue' we use, this produces a where clause that looks like this: WHERE name in ('Vito', 'Joey', 'Vinny'). The starting and ending single quote in the query wraps them all so the syntax is correct.

a millon thanks to you for solving this.


What about the security of this method, is it considered SAFE?!
If not how it can be secured.

Thank you!

@klaus.veliu - Safe version is

    $prep=str_pad("?",count($users)*2-1,",?"); // produce string '?,?,?'
    $sql = "SELECT * FROM `users` WHERE `name` in (".$prep.")";
    $stmt = $db->prepare($sql);
    $result = $stmt->fetchAll(PDO::FETCH_ASSOC);


    $sql = "SELECT * FROM `users` WHERE FIND_IN_SET(`name`,?)";
    $stmt = $db->prepare($sql);
    $result = $stmt->fetchAll(PDO::FETCH_ASSOC);