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);

Please!!!! Sir tell if i want to find specific name form the database where a string of different name is lying throught SELECT query please can you help me how could I tackle this??

hey litlemaster

you can check this out program
$query = "SELECT interests FROM signup WHERE username = '$username'";
$result = mysql_query($query) or die ("no query");
while($row = mysql_fetch_array($result))

echo $row['interests'];
echo "

may be this help you if not then tell me let you know more in deep

commented: Be timely. -3
Be a part of the DaniWeb community

We're a friendly, industry-focused community of 1.18 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.