CakePHP 4 Get Single Row Data From Database Tutorial

Reading Time: 4 minutes
2,139 Views

In this article we will discuss i.e CakePHP 4 get single row data from database. Basically cakephp works with several ways by which we can execute database queries like for Insert, Update, Select, Delete, etc.

Article contains classified information about the topic of getting single row from list of data sets from database. In CakePHP we have options are using ConnectionManager instance, Query Builder object and by Model & Entity to work with database.

We will discuss about How to get single row using Connection Manager Instance and by Model based query.

Learn More –

Let’s get started.

CakePHP 4 Installation

To create a CakePHP project, run this command into your shell or terminal. Make sure composer should be installed in your system.

$ composer create-project --prefer-dist cakephp/app:~4.0 mycakephp

Above command will creates a project with the name called mycakephp.

Create Database

To create a database, either we can create via Manual tool of PhpMyadmin or by means of a mysql command.

CREATE DATABASE mydatabase;

Successfully, we have created a database.

Database Connection

Open app_local.php file from /config folder. Search for Datasources. Go to default array of it.

You can add your connection details here to connect with your database. It will be like this –

//...

'Datasources' => [
        'default' => [
            'host' => 'localhost',
            /*
             * CakePHP will use the default DB port based on the driver selected
             * MySQL on MAMP uses port 8889, MAMP users will want to uncomment
             * the following line and set the port accordingly
             */
            //'port' => 'non_standard_port_number',

            'username' => 'root',
            'password' => 'sample@123',

            'database' => 'mydatabase',
            /*
             * If not using the default 'public' schema with the PostgreSQL driver
             * set it here.
             */
            //'schema' => 'myapp',

            /*
             * You can use a DSN string to set the entire configuration
             */
            'url' => env('DATABASE_URL', null),
        ],
  
     //...

//...

You can pass host, username, password and database.

Successfully, you are now connected with the database.

ConnectionManager: Get Single Row Data

ConnectionManager is a class in CakePHP. We use get() method to get the instance of database group. The ConnectionManager class acts as a registry to access database connections your application has. It provides a place that other objects can get references to existing connections.

use Cake\Datasource\ConnectionManager;

To create database instance using Connection Manager, we use like this –

Connection with default group of database.

$object = ConnectionManager::get("default");

Connection with otherDb group of database.

$object = ConnectionManager::get("otherDb");

We will use the returned connection object to perform insert, update, delete and select operations.

Example

To get all rows –

// Select all rows using connection manager instance
public function selectAllProduct()
{
    $results = $this->db
        ->newQuery()
        ->select('*')
        ->from('products')
        ->execute()
        ->fetchAll('assoc');

    print_r($results);
}

To get single row –

// Select single row using connection manager instance
public function selectProduct()
{
    $product_id = 99;

    $results = $this->db
        ->newQuery()
        ->select('*')
        ->from('products')
        ->where([
            "id" => $product_id
        ])
        ->execute()
        ->fetch('assoc');

    print_r($results);
}

Model & Entity: Get Single Row Data

Model provides the mediator between the working of application with database. Every model in CakePHP represents a database table. An Entity class signifies a single row representation.

Example

To load a model into application –

$this->loadModel("Products");

To get all rows

// Get all data
public function getProducts()
{
    $products = $this->Products
        ->find()
        ->toList();

    print_r($products);
}

To get single row –

// Get single data row
public function getSingleProduct()
{
    $product = $this->Products
        ->find()
        ->order(["id" => "desc"])
        ->first();

    print_r($product);
}

Raw Query: Get Single Row Data

Execution of Raw queries in application means we need to put complete query and then run. We need this approach in case of MySQL complex queries, running stored procedure, etc.

Connection Manager Instance

use Cake\Datasource\ConnectionManager;

To create database instance using Connection Manager, we use like this –

Connection with default group of database.

$db = ConnectionManager::get("default");

Execute Raw Query

If we want to fetch data in bulk then this will be format. It will return results set in array format.

$db->execute("YOUR RAW QUERY")->fetchAll('assoc');

In case of single row value, we will use this

$db->execute("YOUR RAW QUERY")->fetch('assoc');

We hope this article helped you to learn about CakePHP 4 Get Single Row Data From Database Tutorial in a very detailed way.

Online Web Tutor invites you to try Skillshike! Learn CakePHP, Laravel, CodeIgniter, Node Js, MySQL, Authentication, RESTful Web Services, etc into a depth level. Master the Coding Skills to Become an Expert in PHP Web Development. So, Search your favourite course and enroll now.

If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.

Sanjay KumarHello friends, I am Sanjay Kumar a Web Developer by profession. Additionally I'm also a Blogger, Youtuber by Passion. I founded Online Web Tutor and Skillshike platforms. By using these platforms I am sharing the valuable knowledge of Programming, Tips and Tricks, Programming Standards and more what I have with you all. Read more