Execute Custom Queries and SQL in CakePHP 3 & 4

Execute Custom & Parameterized SQL in CakePHP 4 & CakePHP 3

CakePHP4:

Add in your controller:

use Cake\Datasource\ConnectionManager;

Example 1:

$conn = ConnectionManager::get('default');
$stmt = $conn->execute('UPDATE articles SET views_logged_in=views_logged_in+1, some_field=? WHERE id=?', array('some_field_value', $id));

Example 2 - Parameterized with a subquery:

$conn = ConnectionManager::get('default');
$userList = $conn->execute("

 SELECT
   users.id, users.username, users.first_name, users.last_name, users.organization_name, users.email
FROM
  users
WHERE
 users.is_deleted<>'1' AND
 users.id <> :origUserId AND
    users.id IN (
        SELECT
                user_id
        FROM
                grant_applications
        WHERE
                is_deleted <> 1
        GROUP BY user_id
        ) ",  [  'origUserId' => $origUserId ]
 )->fetchAll('assoc');

 

CakePHP3:

Add in your controller:

use Cake\Datasource\ConnectionManager;
$conn = ConnectionManager::get('default');
$stmt = $conn->execute('SELECT * FROM customers');
$results = $stmt ->fetchAll('assoc');      

 

Share this Post