André Luiz
André Luiz

Reputation: 7302

Phalcon PhP - how to execute query inside a controller with parameters

I would like to know how can I execute a query, inside a phalcon controller, using parameters.

My SQL Query:

SELECT a.*, getApplicationData(a.id) as json_data 
FROM application a 
INNER JOIN application_data d on d.application_id = a.id 
WHERE a.form_id=1 
AND d.firstname LIKE '%:searchQuery:%' ;

Here is how I'm trying to execute (I found it in Phalcon's doc, but the example was not inside a controller).

$applications = $this->db->query(
    $sqlQuery, 
    array('searchQuery'=>$searchQuery)
)->fetchAll();

I know that since you have the ORM I shouldn't be querying the DB like this, but for the feature I'm working on it has to be like this, this query is dymanic.

My question is how to pass the parameter for the :searchQuery: in the query.

Thanks in advance for any help.

Upvotes: 2

Views: 2299

Answers (1)

Nikolay Mihaylov
Nikolay Mihaylov

Reputation: 3876

You almost got it right. You only had to add the percents (%) in the bind array.

$sqlQuery = 'SELECT * FROM events WHERE title LIKE :searchQuery';
$applications = $this->db->query(
    $sqlQuery, 
    array('searchQuery'=> '%' . $searchQuery . '%')
)->fetchAll();

Also notice how I binded the :searchQuery in the $sqlQuery. It only uses single : instead of surrounding the parameter. This is because Raw queries use directly the DB connection in our case it is PDO.

More examples can be found here: https://docs.phalconphp.com/en/latest/api/Phalcon_Db_Adapter_Pdo.html

Upvotes: 3

Related Questions