带有SELECT OR的mysql PDO,错误!:SQLSTATE [HY093]

时间:2015-06-10 18:51:04

标签: php mysql pdo

我有一个简单的搜索表单,它向我的php文件发送一个post请求,其中包含像"searchword=test1"这样的输入。然后我使用它与PDO在我的表中搜索mathing数据。

到目前为止,我只使用以下语句搜索一列:

$query = $db->prepare("SELECT * FROM articles WHERE title LIKE :seachword);

但现在我想搜索3列(命名为title,extract和body)。我将代码更改为:

$query = $db->prepare("SELECT * FROM articles WHERE title LIKE :seachword OR extract LIKE :searchword OR body LIKE :searchword");

现在我收到错误"Error!: SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens<br/>"

如果我使用bash(SELECT * FROM articles WHERE title LIKE '%test%' OR body LIKE '%elem%';)运行SQL语句,查询结果将返回正常。

知道我缺少什么吗?

这是我的代码:

<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

try {
    $hostname = "localhost";
    $username = "root";
    $password = "";

    $db = new PDO("mysql:host=$hostname;dbname=topdecka_PTC",$username, $password);
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    if (!empty($_POST["searchword"])) {
        $searchword = $_POST["searchword"];
        $query = $db->prepare("SELECT * FROM articles WHERE title LIKE :seachword OR extract LIKE :searchword OR body LIKE :searchword");
        $query->execute(array(":seachword" => "%" . $searchword . "%"));

        $result = $query->fetchAll(PDO::FETCH_ASSOC);
        echo json_encode($result);
        die();
    } 
    else {
        $query = $db->prepare('SELECT * FROM articles');
        $query->execute();

        $result = $query->fetchAll(PDO::FETCH_ASSOC);
        echo json_encode($result);
        die();
    }
} catch (PDOException $e) {
    echo "Error!: " . $e->getMessage() . "<br/>";
    die();
}
?>

1 个答案:

答案 0 :(得分:3)

你有一个拼写错误:2 x :seachword和2 x :searchword