1
SELECT * FROM `orders` WHERE id LIKE %1%
Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error or access violation: 1064 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 '%1%' at line 1

PHP

$sql = "SELECT * FROM `orders` ";

switch ($_POST['criteria']) {

    case 'id':
        $sql .= "WHERE id LIKE %" . (int) $_POST['search_input'] . "%";
    break;
    case 'OCR':
        $sql .= "WHERE OCR LIKE %" . $db->quote($_POST['search_input']) . "%";
    break;
    case 'name':
        $arr = explode(' ', $_POST['search_input']);
        $firstname = $arr[0];

        if (isset($arr[1])) {
            $lastname = $arr[1];
        } else {
            $lastname = null;
        }

        $sql .= "WHERE firstname LIKE %" . $db->quote($firstname) . "% AND lastname LIKE %" . $db->quote($lastname) . "%";
    break;
}

echo $sql;

$stmt = $db->query($sql);

$rows = $stmt->fetchAll();

查询正在输出,对我来说看起来不错,但由于某种原因,我遇到了语法错误(我认为是),但是我似乎没有发现任何问题?

4

3 回答 3

3

您的字符串周围缺少引号,因此您的查询类似于:

SELECT * FROM orders where id LIKE %55%

代替:

SELECT * FROM orders where id LIKE '%55%'


$sql = "SELECT * FROM `orders` ";

switch ($_POST['criteria']) {

    case 'id':
        $sql .= "WHERE id LIKE '%" . (int) $_POST['search_input'] . "%'";
    break;
    case 'OCR':
        $sql .= "WHERE OCR LIKE '%" . $db->quote($_POST['search_input']) . "%'";
    break;
    case 'name':
        $arr = explode(' ', $_POST['search_input']);
        $firstname = $arr[0];

        if (isset($arr[1])) {
            $lastname = $arr[1];
        } else {
            $lastname = null;
        }

        $sql .= "WHERE firstname LIKE '%" . $db->quote($firstname) . "% AND lastname LIKE '%" . $db->quote($lastname) . "%'";
    break;
}

echo $sql;

$stmt = $db->query($sql);

$rows = $stmt->fetchAll();

这个答案应该可以解决您的问题,但我强烈建议您使用=,而不是LIKE因为您正在寻找由id.

您当前编写脚本的方式,如果id是 55,您将收到订单 55、255、5500、1559...

于 2013-08-11T15:30:07.497 回答
3

LIKE运算符是一个字符串函数。所以你需要用单引号(')将它括起来。

SELECT * FROM `orders` WHERE id LIKE '%1%';
于 2013-08-11T15:26:40.010 回答
2

请在单个 qoute '' 中写模式,并像我一样确定

         incorrect     SELECT * FROM `orders` WHERE id LIKE %1%
           correct-     SELECT * FROM `orders` WHERE id LIKE '%1%' 
于 2013-08-11T15:32:42.197 回答