【问题标题】:PHP mysql select query where (wildcard)PHP mysql select查询where(通配符)
【发布时间】:2012-12-08 01:03:18
【问题描述】:

我正在尝试使用以下 MySQL 查询,但显然有问题。我正在尝试使 page.phppage.php?q= 返回以下查询:

if (!isset($_GET['q'])) { $where = "WHERE column1 LIKE %"; }
else { $where = "WHERE column1 LIKE ".$_GET['q']; }

$query = "SELECT column1, column2 FROM table '$where' GROUP BY column1";

所以如果没有 GET,那么 MySQL 查询中就没有 WHERE。我将 GET 设置为某个值,然后有一个带有该 GET 值的WHERE

目前我收到以下错误:

您的 SQL 语法有错误;检查手册 对应于您的 MySQL 服务器版本,以便使用正确的语法 在第 1 行的 ''WHERE column1LIKE 'GROUP BY column1' 附近

【问题讨论】:

  • 您的代码很容易受到 SQL 注入攻击。请使用参数化查询。
  • 谢谢Dai。目前这只是一个临时页面。我不会很长时间,并且只在 Intranet 上。

标签: php mysql wildcard


【解决方案1】:

您需要使用某种形式的转义,但这是另一天的练习。如果您只是想让它工作,请删除 where 变量周围的单引号。

$query = "SELECT column1, column2 FROM table $where GROUP BY column1";

【讨论】:

    【解决方案2】:

    对于使用PDO 的通用解决方案,试试这个 sn-p(其中 $db 是 PDO 连接对象)。

    $params = array();
    
    $sql = 'SELECT column1, column2 FROM table where 1 ';
    
    if (!empty($_GET['q'])) {
        $sql .= " column1 like ?";
        $params[] = '%' . $_GET['q'] . '%';
    }
    
    if (!empty($_GET['r'])) {
        $sql .= " column2 like ?";
        $params[] = '%' . $_GET['r'] . '%';
    }
    
    $sql .= ' GROUP BY column1 ORDER BY column1';
    
    $query = $db->prepare($sql);
    $i = 1;
    foreach ($params as $param) {
        $query->bindValue($i, $param);
        $i++;
    }
    $query->execute();
    

    【讨论】:

    • 谢谢,我更新了我的 PDO 脚本,以上内容帮助我解决了问题。
    【解决方案3】:

    您需要将搜索字符串放在单引号之间的WHERE 子句中,如下所示:

    $where = "";
    // if there the get q is set we add the were clause
    if (!isset($_GET['q'])) {
        $where = "WHERE column1 LIKE %";
        // ^ This WHERE clause is useless, since it matches all strings.
        // Omitting this WHERE clause has the same effect.
    }
    else { $where = "WHERE column1 LIKE ".$_GET['q']; }
    
    $query = "SELECT column1, column2 FROM table ".$where." GROUP BY column1";
    

    注意您的脚本极易受到攻击。 Read about SQL-injections.

    【讨论】:

      【解决方案4】:

      我认为您可以简单地这样做: 顺便说一句..你不需要其他部分“”类似%“”你可以简单地省略 where 子句,它会产生相同的效果...... 这是您刚刚发布的内容的副本:

      $where = "";
      //if there the get q is set we add the where clause
      if(isset($_GET['q'])) { 
         $where = "WHERE column1 LIKE '".$_GET['q']."'"; 
      }
      
      $query = "SELECT column1, column2 FROM table ".$where." GROUP BY column1";
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-02-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-06-22
        • 1970-01-01
        相关资源
        最近更新 更多