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.

Recommended Answers

All 8 Replies

<?php
$users=array("sure","ronald","us");
$foundRows=array();
$query="SELECT * FROM users WHERE ";
foreach($users as $name)
{
$query="SELECT * FROM users WHERE name='$name'";
$res=mysql_query($query,$link);
while($row=mysql_fetch_assoc($res))
{
//Push the rows you have found to the foundRows array declared above
array_push($foundRows,$row);
}
}

print_r($foundRows);
?>

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

$users=array("Vito","Joey","Vinny");

// 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.

Hello,

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

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

or

    $users=array("Vito","Joey","Vinny");
    $sql = "SELECT * FROM `users` WHERE FIND_IN_SET(`name`,?)";
    $stmt = $db->prepare($sql);
    $stmt->execute([implode(",",$users)]);
    $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 "<br />";

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

commented: Be timely. -3

Thank you.

Be a part of the DaniWeb community

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