【问题标题】:PHP Search Generates ErrorPHP 搜索产生错误
【发布时间】:2012-09-12 04:43:34
【问题描述】:

我的网站上有一个搜索字段功能,PHP 代码如下:

if(isset($_GET['search_ti']) && $_GET['search_ti'] != "")
{
    $search_ti = preg_replace('#[^a-z 0-9?!-]#i', '', $_GET['search_ti']);

    $sqlCommand = "
    SELECT * FROM page WHERE title LIKE '%$search_ti%' OR body LIKE '%$search_ti%'
    ";

    $result = $mysqli->query($sqlCommand) or die(mysql_error());
    ...

URL 变量search_ti 是搜索的关键字,是我从URL 中得到的。例如:

searchResult.php?search_ti=home

如果在我的 MySQL 表中找到关键字,结果显示并且没有错误。

但是如果没有找到关键字,网页浏览器会产生以下错误:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '-4,4' at line 1

我的代码有什么问题?

附加信息:

完整的PHP代码:http://jsfiddle.net/eQSZc/

关键词:家。该错误仅在我的表中未找到该关键字时显示。

【问题讨论】:

  • 我们需要更多您的代码...第 1 行有什么内容?
  • 您能否将查询粘贴到您的问题中引发错误?
  • 该错误似乎与另一个查询有关。片段“-4,4”没有出现在您这里的代码中。
  • 你试过 echo $sqlCommand;出口;看看它生成了什么查询?
  • 添加了一个粘贴版本pastie.org/4705905颜色编码。

标签: php mysql search mysqli sql-like


【解决方案1】:

将您的pagination_mechanism_and_buttons_variables_for_Search.php 更改为http://jsfiddle.net/GsNmw/1/ 中的那个

在您构造 $limit 并更改 $limit 之前,我添加了以下块。

$start = ($pn - 1) * $itemsPerPage;

if($start<0){
    $start = 0;
}

$limit = 'LIMIT ' .$start .',' .$itemsPerPage;

这避免了负限制,从而避免了你的错误。

【讨论】:

    【解决方案2】:

    另一种方法是使用 PDO。

    <?php
    $dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
    $keyword = '%' . search_ti . '%';
    $stmt = $dbh->prepare("SELECT * 
                           FROM page 
                           WHERE title LIKE ? OR 
                                 body LIKE ?");
    $stmt->bindParam(1, $name);
    if ($stmt->execute())
    {
      while ($row = $stmt->fetch()) 
      {
        print_r($row);
      }
    }
    ?>
    

    这将允许您选择带单引号的记录。

    【讨论】:

    • 谢谢,但我不明白如何将我的代码转换为 PDO。以后我会努力学习的
    猜你喜欢
    • 1970-01-01
    • 2020-12-26
    • 2014-06-21
    • 1970-01-01
    • 2013-03-09
    • 2017-12-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多