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

时间:2017-07-07 11:40:41

标签: php mysql where-in

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

$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 ";

任何人都可以帮我吗?

4 个答案:

答案 0 :(得分:3)

join(implode)函数中有一些缺少的单引号:

$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')...

此处每个查询都会在多个搜索值中正确分割。

答案 1 :(得分:0)

$query = "select * from sites where site_keywords in (".implode(",",$keywords).") order by rank DESC ";

答案 2 :(得分:0)

IN进行字面搜索,进行“模糊”搜索,您需要执行以下操作:

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

答案 3 :(得分:0)

始终使用预准备语句来阻止SQL注入。以下代码可用作解决问题的起点(需要PDO库http://php.net/manual/en/book.pdo.php)。

$user_query = $_REQUEST['user_query'];                      // you should better use $_GET or $_POST explicitly
$user_query = preg_replace('#\s{2,}#', ' ', $user_query);   // replace multiple spaces with a single space
$keywords = explode(' ', $user_query);                      // create the keywords array
$placeholders = array_fill(0, count($keywords), '?');       // create the placeholders array

$sql = 'SELECT *
        FROM sites
        WHERE site_keywords IN (' . implode(', ', $placeholders) . ')
        ORDER BY rank DESC';

$stmt = $db->prepare($sql);
$stmt->execute($keywords);
$result = $stmt->fetchAll();