Question

I am converting old mysql_query code to PDO parameterized queries. Here's what I have so far. It doesn't seem to return anything. I have tried the same query in phpmyadmin, and in the old code with the same input, and the query returns rows those ways.

public function searchArticle($input)
{
 $db = new PDO("mysql:host=localhost;dbname=thecorrectdbname", "root", "supersecretpassword");    

    $statement = $db->prepare("SELECT * FROM news WHERE headline LIKE '%:title%'
                            OR content LIKE %:content%'
                            OR author LIKE '%:author%'
                            ORDER BY id DESC");

    $statement->execute(array('title' =>$query, 
                            'content' =>$query,
                            'author'=>$query));

    $result = $statement->fetchAll();

    print_r($result);

    if (!$result || $statement->rowCount() <= 0)
    {
        echo'nothing in this array';
        return false;
    }

    return $result;
 }

This returns

 Array ( ) nothing in this array 

Using the same $db connection I can manage to INSERT data into the DB, so the connection is working.

Two questions.

  1. What am I doing wrong in this code?

  2. Suppose I would get the code working. Is the $result object returned by a PDO prepared statement structurally the same as a mysql_query $result object? If not, how do I convert a PDO resultset to a mysql_query one?

Was it helpful?

Solution

Your replacement variables will get escaped and quoted automatically by PDO, which means you cannot have a variable within quotes.

change the following:

$statement = $db->prepare("SELECT * FROM news WHERE headline LIKE :title
                            OR content LIKE :content
                            OR author LIKE :author
                            ORDER BY id DESC");

$statement->execute(array('title' =>'%'.$query.'%', 
                            'content' =>'%'.$query.'%',
                            'author'=>'%'.$query.'%'));

OTHER TIPS

You are doing an invalid use of placeholder. Placeholder must be used in the place of whole value.

$statement = $db->prepare("SELECT * FROM news WHERE headline LIKE :title
                        OR content LIKE :content
                        OR author LIKE :author
                        ORDER BY id DESC");

$statement->execute(array('title' =>"%$query%", 
                        'content' =>"%$query%",
                        'author'=>"%$query%"));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top