Trongate Docs
switch to dark modeswitch to dark mode
»
»
The 'Query Bind' Method

The 'Query Bind' Method

The 'Query Bind' method executes custom SQL queries.  Unlike, the 'Query' method, this method uses PDO query binding which makes SQL injection impossible - provided you use the method properly.

Query Binding Tutorial

Here's a video, covering everything you need to know about how to do query binding with Trongate

Top Tip
The 'Query Bind' method offers a much safer way to run custom SQL queries than the previously mentioned 'Query' method.  Make this your 'go to' method for running custom SQL queries.

The following parameters can be accepted by the 'Query Bind' method:

  • $sql (required) - the SQL query that you would like to execute on your database.
  • $params (required) - an array of key, value pairs that can be safely used by PDO to replace placeholder values.
  • $return_type (option) - the data type for table rows that are returned from the query.  Acceptable values for this are 'object' and 'array'.

Just To Let You Know
If you leave $return_type empty then any table rows that are returned from your query will be objects.

What Gets Returned?

WHEN MATCHING RECORDS ARE FOUND

If matching records are found then a PHP array will be returned where each item on the array represents a row from a database table. Each row, within the array, will either be a PHP object or a PHP array.

WHEN MATCHING RECORDS ARE NOT FOUND

If the SQL query produces no results then an empty array will be returned.

Example 1

The syntax below shows an example of query binding using named parameters.

function test() {
    $params['first_name'] = 'Starsky';

    $sql = 'SELECT *
            FROM members
            WHERE first_name = :first_name';

    $rows = $this->model->query_bind($sql, $params, 'object');
    json($rows);
}

The code above will produce the following SQL query:

SELECT * FROM members WHERE first_name = 'Starsky'

Example 2

Below is an example of query binding using unnamed parameters:

​function test() {
​    $params[] = 'Starsky';
    $params[] = 'Star';

​    $sql = 'SELECT *
            FROM members
            WHERE first_name = ?
            AND last_name = ?';

​    $rows = $this->model->query_bind($sql, $params, 'object');
​    json($rows);
​}

The code above would produce the following SQL query:

SELECT * FROM members WHERE first_name = 'Starsky' and last_name = 'Star'

Top Tip
Create complex table joins in seconds with the Trongate Graphical Query builder.


HELP & SUPPORT

If you have a question or a comment relating to anything you've see here, please goto the Help Bar.

 
×