如何在单个查询中搜索多个用户名

时间:2016-05-08 21:24:32

标签: php mysql

我想在我的数据库中搜索一些用户名,例如this->

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

现在字符串变量看起来像“name1,name2,name3”;

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

这会提取用户,但我不想要这些用户。我的意思是有任何查询,我可以写WHERE username !in ({$string})

获取除“name1,name2,name3”这些用户

之外的所有用户

现在添加NOT IN后我收到错误

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'

3 个答案:

答案 0 :(得分:2)

您应该使用NOT IN排除某些值。

mysqli_query($db, "SELECT * FROM users WHERE username NOT IN ('name1', 'name2') ORDER BY id DESC");

答案 1 :(得分:2)

在SQL查询中尝试NOT IN

首先尝试在sql查询的NOT IN部分中为您尝试的值添加引号。

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

然后在查询中使用此$str。另外,尝试使用``作为列名来养成习惯,如下所示:

SELECT `SOMETHING` FROM `TABLE_NAME` WHERE <CONDITION>

我希望有所帮助!

答案 2 :(得分:1)

是的,只需输入&#34;不是&#34;而不是&#34;!&#34;

从表格中选择*不在其中的垃圾(&#39; item1&#39;,&#39; item2&#39;,&#39; item3&#39;);

1)虽然你没有为你的内幕添加引号,但你还有其他一些问题:

// you need quotes here
$string = implode("','", $str);
// And here
mysqli_query($db, "SELECT * FROM users WHERE username in ('{$string}') ORDER BY id DESC");

然而,这是真正正在做的事情。

2)当你打开SQL注入时,你应该绑定你的参数:

$params = array();
$params[0] = "";
$sql = "SELECT * FROM users WHERE username NOT IN (";
foreach($str as $s){
    $params[0] .= "s";
    array_push($params, $s);
    $sql .= "?, ";
}
$sql = rtrim($sql, " ,").") ORDER BY id DESC";

$stmt = $conn->prepare($sql);

// this is the same as doing: $stmt->bind_param('s', $param);
call_user_func_array(array($stmt, 'bind_param'), $params);

// execute and get results
$stmt->execute();