简体   繁体   中英

mysql PDO with SELECT OR, Error!: 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();
}
?>

您有错别字:2 x :seachword和2 x :searchword

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM