Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/294.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在php mysql查询中使用数组?_Php_Mysql_Where In - Fatal编程技术网

如何在php mysql查询中使用数组?

如何在php mysql查询中使用数组?,php,mysql,where-in,Php,Mysql,Where In,我一直在尝试从数据库中检索所有site_关键字,使用$keyword中的where site_关键字。但它没有显示任何错误或输出 $user_query = $_REQUEST['user_query']; $search=preg_split('/\s+/',$user_query); $keywords = join(",",$search); $query = "select * from sites where site_keywords in ('%$keywords%') orde

我一直在尝试从数据库中检索所有site_关键字,使用$keyword中的where site_关键字。但它没有显示任何错误或输出

$user_query = $_REQUEST['user_query'];
$search=preg_split('/\s+/',$user_query);
$keywords = join(",",$search); 
$query = "select * from sites where site_keywords in ('%$keywords%') order by rank DESC ";

有人能帮我吗

连接(内爆)函数中缺少一些单引号:

$user_query = $_REQUEST['user_query'];
$search=preg_split('/\s+/',$user_query);
$keywords = join("','",$search); 
$query = "select * from sites where site_keywords in ('%$keywords%') order by rank DESC ";
不带这些引号的查询:

...where site_keywords in ('one,two,three')...
...where site_keywords in ('one','two','three')...
这不会产生任何输出或错误,因为没有有效的结果。搜索查询被视为一个长字符串

使用这些引号进行查询:

...where site_keywords in ('one,two,three')...
...where site_keywords in ('one','two','three')...

在这里,每个查询被正确地分割为多个搜索值。

中的执行文字搜索,要执行“模糊”搜索,您需要执行以下操作:

$query = "select * from sites where site_keywords in (".implode(",",$keywords).") order by rank DESC ";
$query = "SELECT * FROM sites WHERE ".implode(" OR ", array_fill(0,count($search),"site_keywords LIKE ?"); 
 //Query looks like SELECT * FROM sites WHERE site_keywords LIKE ? OR site_keywords LIKE ?

$search = array_map(function ($v) { 
    return "%$v%";
},$search); 
现在,对于绑定,它取决于您使用的是什么:

//MySQLi 
$stmt = mysqli_prepare($connection, $query);
mysqli_stmt_bind_param($stmt, array_fill(0,count($search),"s"), ...$search); //Note, you may bet some issues with references here. 
mysqli_stmt_execute($stmt);

//PDO
$stmt = $connection->prepare($query); 
for ($i = 0;$i< $search;$i++) {
    $stmt->bindValue($i+1,$search[$i]);
} 
$stmt->execute();
//MySQLi
$stmt=mysqli\u prepare($connection,$query);
mysqli_stmt_bind_param($stmt,array_fill(0,count($search),“s”),…$search)//请注意,您可能会在这里打赌一些引用问题。
mysqli_stmt_execute($stmt);
//PDO
$stmt=$connection->prepare($query);
对于($i=0;$i<$search;$i++){
$stmt->bindValue($i+1,$search[$i]);
} 
$stmt->execute();

始终使用准备好的语句来防止SQL注入。以下代码可以作为解决问题的起点(需要PDO库,)


您的脚本有可能会被使用。请使用
mysqli\u query()
$\u REQUEST['user\u query']]
执行您的查询。假设user\u query=“在这方面有疑问”,那么如果我们使用的是连接函数,$keywords变为got'、'a'、'疑'、'in','this--则查询没有搜索get和this。若我在前后加上“before”和“after”,那个么查询就失败了。那我该怎么做呢?