【问题标题】:how to use an array in php mysql query?如何在 php mysql 查询中使用数组?
【发布时间】:2017-12-11 16:48:23
【问题描述】:

我一直在尝试使用 $keyword 中的 where 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 ";

谁能帮我解决这个问题?

【问题讨论】:

标签: php mysql where-in


【解决方案1】:

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

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

【讨论】:

  • 假设 user_query="got a question in this",那么如果我们使用 join 函数,$keywords 就变成 got','a','doubt','in','this --然后查询不搜索 got 和 this。如果我在前后附加 ',则查询失败。那我该怎么做呢?
【解决方案2】:
$query = "select * from sites where site_keywords in (".implode(",",$keywords).") order by rank DESC ";

【讨论】:

    【解决方案3】:

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

    【讨论】:

      【解决方案4】:

      始终使用准备好的语句来防止 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();
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-07-31
        • 1970-01-01
        • 2011-03-31
        • 1970-01-01
        • 2014-04-19
        • 1970-01-01
        • 2022-01-23
        • 1970-01-01
        相关资源
        最近更新 更多