MySQL query with PDO does not return data

2

I have the following problem. I developed a PHP class for a site I'm creating and in one of those functions I'm having a problem with the PDO. When giving the command SELECT I use the rowCount () function to check if it has obtained results and the result obviously is 0 rows. I have already tested QUERY and includes it and it 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;
}

Return is always postArray['status'] //false

    
asked by anonymous 30.12.2016 / 07:31

1 answer

4

Query should not return results even because of those single quotes and wildcards (% with%). In other words, simple quotes will override their placeholder, instead of looking for % will look for %termo digitado% .

To solve, remove the single quotation marks and pass the congestions in% with%

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 binds to:

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

In all %:tl% s have spaces ( bindValue() ), if they were intentional add them in bind.

$find->bindValue(":tl", '% '. $s .' %',  PDO::PARAM_STR);
espaço extra--------------^        ^--------------espaço extra
    
30.12.2016 / 15:16