Sagar Singh Sagar Singh - 5 months ago 6
SQL Question

how to search multiple username in a single query

I want to search for some username in my database like this->

$skip = $_POST['username'];
$_SESSION['skip_user'] = array();
$str = $_SESSION['skip_user'];
$string = rtrim(implode(',', $str), ',');

Now string variable looks like "name1, name2, name3";

mysqli_query($db, "SELECT * FROM users WHERE username in ({$string}) ORDER BY id DESC");

This fetches the users but i don't want these users. I mean is there any query where i can i write
WHERE username !in ({$string})

get all users except "name1, name2, name3" these users

Now after adding NOT IN I'm receiving error

mysqli_query($db, "SELECT * FROM users WHERE username NOT IN ({$string}) ORDER BY id DESC")or die(mysqli_error($db)); php is giving error Unknown column 'name1' in 'where clause'


Try NOT IN in the SQL query.

First though try to add quotes to the values you are trying in the NOT IN part of the sql query.

$str = '';
foreach ($_SESSION['skip_user'] AS $word) {
    $str .= "'$word',";
$str = rtrim($str, ',');

Then use this $str in your query. Also, try to make a habit out of using `` for column names, like this:


I hope that helps!