Mysql query with PDO does not return data

Asked

Viewed 150 times

3

I have the following problem. I have developed a PHP class for a site I am creating and in one of these functions I am having problems with PDO. In giving the command SELECT I use the rowCount() function to check if you got results and the result is obviously 0 Rows. I already tested the QUERY and includes and is working normally.

Function code:

public function search($s) {
    $db = $this->db;
    $find = $db->prepare("SELECT `id`, `type`, `title`,`coverofpost`, `date` FROM `posts` WHERE title LIKE '% :tl %' OR tags LIKE '% :tags %' OR post LIKE '% :post %'");
    $find->bindValue(":tl", $s, PDO::PARAM_STR);
    $find->bindValue(":tags", $s, PDO::PARAM_STR);
    $find->bindValue(":post", $s, PDO::PARAM_STR);
    $find->execute();
    if ($find->rowCount() > 0) {
        $this->mountArray();
        while ($data = $find->fetch(PDO::FETCH_ASSOC)) {
            array_push($this->id, $data['id']);
            array_push($this->type, $data['type']);
            array_push($this->title, $data['title']);
            array_push($this->cover, $data['coverofpost']);
            array_push($this->time, $data['date']);
        }
        $this->makeUrls();
        $this->makeArray();
        $this->postArray['status'] = true;
    } else {
        $this->postArray['status'] = false;
    }
    return $this->postArray;
}

The return is always postArray['status'] //false

  • 1

    Remove the simple quotes from the query and pass the % in the bindValue()

1 answer

5


The query should not return results even due to those simple quotes and the jokers (%). That is, the single quotes will undo your placeholder instead of searching %termo digitado% go find %:tl%.

To resolve remove the single quotes and pass the conringas on bindValue()

Change your query to:

SELECT `id`, `type`, `title`,`coverofpost`, `date`
FROM `posts` WHERE title LIKE :tl OR tags LIKE :tags OR post LIKE :post 

And the Banks to:

$find->bindValue(":tl", '%'. $s .'%',  PDO::PARAM_STR);
$find->bindValue(":tags", '%'. $s .'%', PDO::PARAM_STR);
$find->bindValue(":post", '%'. $s .'%', PDO::PARAM_STR);

In all LIKEs has spaces (LIKE '% :tl %'), if they were intentional add them to the bind.

$find->bindValue(":tl", '% '. $s .' %',  PDO::PARAM_STR);
espaço extra--------------^        ^--------------espaço extra
  • Solved. Thank you very much!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.