Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to execute custom query in cakephp 3.x

Custom query execution in cakephp. I have applied below code.

$conn = ConnectionManager::get('default');

$rs = $conn->query('SELECT * FROM customers');

It gives me blank array though customers table has 20 records.

Please suggest me some solution.

Thanks.

like image 546
Khushang Bhavnagarwala. Avatar asked Jan 01 '16 05:01

Khushang Bhavnagarwala.


1 Answers

It's not recommended but somtimes there is no other way! :

  1. You should mention namespace of connection manger

    use Cake\Datasource\ConnectionManager;
    
  2. Get/initialize a connection

    $conn = ConnectionManager::get('default');
    
  3. Execute SQL with something like this

    $stmt = $conn->execute('SELECT * FROM customers');
    
  4. Fetch the results

    $results = $stmt ->fetchAll('assoc');
    

See also

  • Cookbook > Database Access & ORM > Database Basics > Running Select Statements
  • API > \Cake\Database\SatementInterface::fetch()
  • API > \Cake\Database\SatementInterface::fetchAll()
like image 159
MSS Avatar answered Sep 29 '22 18:09

MSS