Maria Zelenova
Maria Zelenova

Reputation: 37

Prepared default query with result to prepared query with bindings

I have a query that is working but is does not have binded values:

$this->_db->query("SELECT * from posts WHERE post_title LIKE '%$this->search_keywords%' OR post_content LIKE '%$this->search_keywords%' LIMIT 100");
$this->rows_results_found = $this->_db->resultset();

$this->results_found_num = sizeof($this->rows_results_found);

I am rewriting it to this one but with no luck:

$this->_db->query('SELECT * from posts WHERE post_title LIKE :search_keywords OR post_content LIKE :search_keywords LIMIT 100');
            $this->_db->bind(':search_keywords', '%$this->search_keywords%');

            $this->rows_results_found = $this->_db->resultset();

            $this->results_found_num = sizeof($this->rows_results_found);

$this->results_found_num appears always to be an empty array.

This is what I have in the resultset() (It is from another outer class):

public function resultset() {
        $this->execute();
        return $this->stmt->fetchAll(PDO::FETCH_ASSOC);
    }

What I am missing here?

Thank you in advance!

Upvotes: 0

Views: 30

Answers (1)

meda
meda

Reputation: 45490

Assuming you have a valid connection adjust your function to the following:

public function get_posts($conn) {
    $query = 'SELECT * 
              FROM posts 
              WHERE post_title LIKE :search_keywords1 OR 
                    post_content LIKE :search_keywords2 LIMIT 100';
    $stmt = $conn->prepare($query);
    $stmt->bindValue(':search_keywords1', '%'.$this->search_keywords.'%');
    $stmt->bindValue(':search_keywords2', '%'.$this->search_keywords.'%');
    $stmt->execute();

    return $stmt->fetchAll(PDO::FETCH_ASSOC);
}

Usage:

$posts = $this->_db->get_posts($conn);
//var_dump($post)
$this->rows_results_found = count($post);

Upvotes: 1

Related Questions