dqxboe2628 2015-06-10 18:51
浏览 29
已采纳

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

I have a simple search form that sends a post request to my php file, that contains the input like this "searchword=test1". I then use that with PDO to search my table for mathing data.

So far I was only searching one column, using this statement:

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

but now I want to search trought 3 columns (named title, extract and body). I changed my code to:

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

and now I get an error saying "Error!: SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens<br/>".

If I run the SQL statement using bash ( SELECT * FROM articles WHERE title LIKE '%test%' OR body LIKE '%elem%';), the query results return fine.

Any idea what I'm missing?

Here's my code:

<?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条回答 默认 最新

  • dongya5893 2015-06-10 18:56
    关注

    You have a typo: 2 x :seachword and 2 x :searchword

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化