亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

Table of Contents
Insert a Record
Example
Output
Home Backend Development PHP Tutorial CakePHP Working with Database

CakePHP Working with Database

Sep 10, 2024 pm 05:25 PM
php cakephp PHP framework

Working with database in CakePHP is very easy. We will understand the CRUD (Create, Read, Update, Delete) operations in this chapter.

Further, we also need to configure our database in config/app_local.php file.

'Datasources' => [
   'default' => [
      'host' => 'localhost',
      'username' => 'my_app',
      'password' => 'secret',
      'database' => 'my_app',
      'url' => env('DATABASE_URL', null),
   ],
   /*
      * The test connection is used during the test suite.
   */
   'test' => [
      'host' => 'localhost',
      //'port' => 'non_standard_port_number',
      'username' => 'my_app',
      'password' => 'secret',
      'database' => 'test_myapp',
      //'schema' => 'myapp',
   ],
],

The default connection has following details ?

'host' => 'localhost',
   'username' => 'my_app',
   'password' => 'secret',
   'database' => 'my_app',

You can change the details, i.e. host, username, password and database as per your choice.

Once done, make sure it is updated in config/app_local.php in Datasources object.

Now, we will continue with above details, go to your phpmyadmin or mysql database and create user my_app as shown below ?

My App

Give the necessary privileges and save it. Now, we have the database details as per the configuration mentioned in app_local.php. When you check CakePHP home page, this is what you should get ?

App Local

Now, we will create the following users’ table in the database.

CREATE TABLE `users` ( 
   `id` int(11) NOT NULL AUTO_INCREMENT,
   `username` varchar(50) NOT NULL, 
   `password` varchar(255) NOT NULL, PRIMARY KEY (`id`) 
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=latin1

Insert a Record

To insert a record in database, we first need to get hold of a table using TableRegistry class. We can fetch the instance out of registry using get() method. The get() method will take the name of the database table as an argument.

This new instance is used to create new entity. Set necessary values with the instance of new entity. We now have to call the save() method with TableRegistry class’s instance which will insert new record in database.

Example

Make changes in the config/routes.php file as shown in the following program.

config/routes.php

<?php use Cake\Http\Middleware\CsrfProtectionMiddleware;
use Cake\Routing\Route\DashedRoute;
use Cake\Routing\RouteBuilder;
$routes->setRouteClass(DashedRoute::class);
$routes->scope('/', function (RouteBuilder $builder) {
   $builder->registerMiddleware('csrf', new CsrfProtectionMiddleware([
      'httpOnly' => true,
   ]));
   $builder->applyMiddleware('csrf');
   //$builder->connect('/pages',['controller'=>'Pages','action'=>'display', 'home']);
   $builder->connect('/users/add', ['controller' => 'Users', 'action' => 'add']);
   $builder->fallbacks();
});

Create a UsersController.php file at src/Controller/UsersController.php. Copy the following code in the controller file.

src/controller/UsersController.php

<?php namespace App\Controller;
use App\Controller\AppController;
use Cake\ORM\TableRegistry;
use Cake\Datasource\ConnectionManager;
use Cake\Auth\DefaultPasswordHasher;
class UsersController extends AppController{
   public function add(){
      if($this->request->is('post')){
         $username = $this->request->getData('username');
         $hashPswdObj = new DefaultPasswordHasher;
         $password = $hashPswdObj->hash($this->request->getData('password'));
         $users_table = TableRegistry::get('users');
         $users = $users_table->newEntity($this->request->getData());
         $users->username = $username;
         $users->password = $password;
         $this->set('users', $users);
         if($users_table->save($users))
         echo "User is added.";
      }
   }
}
?>

Create a directory Users at src/Template and under that directory create a View file called add.php. Copy the following code in that file.

src/Template/Users/add.php

<?php echo $this->Form->create(NULL,array('url'=>'/users/add'));
   echo $this->Form->control('username');
   echo $this->Form->control('password');
   echo $this->Form->button('Submit');
   echo $this->Form->end();
?>

Execute the above example by visiting the following URL. http://localhost/cakephp4/users/add

Output

Upon execution, you will receive the following output.

CakePHP Working with Database

The data will be saved in the users table as shown below ?

Show All

The above is the detailed content of CakePHP Working with Database. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Grow A Garden - All Animals And How To Get Them
4 weeks ago By 尊渡假賭尊渡假賭尊渡假賭
How to Remove & Clean Ink in Cash Cleaner Simulator
3 weeks ago By 尊渡假賭尊渡假賭尊渡假賭
Roblox: Grow A Garden - Complete Weather Guide
1 months ago By 尊渡假賭尊渡假賭尊渡假賭
Revenge Of The Savage Planet: Every Outfit And How To Unlock It
3 weeks ago By 尊渡假賭尊渡假賭尊渡假賭

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to use JavaScript to determine whether two arrays are equal? How to use JavaScript to determine whether two arrays are equal? May 23, 2025 pm 10:51 PM

In JavaScript, you need to use a custom function to determine whether two arrays are equal, because there is no built-in method. 1) Basic implementation is to compare lengths and elements, but cannot process objects and arrays. 2) Recursive depth comparison can handle nested structures, but requires special treatment of NaN. 3) Special types such as functions and dates need to be considered, and further optimization and testing are required.

How to verify social security number string in PHP? How to verify social security number string in PHP? May 23, 2025 pm 08:21 PM

Social security number verification is implemented in PHP through regular expressions and simple logic. 1) Use regular expressions to clean the input and remove non-numeric characters. 2) Check whether the string length is 18 bits. 3) Calculate and verify the check bit to ensure that it matches the last bit of the input.

How to correctly handle this pointing in a closure? How to correctly handle this pointing in a closure? May 21, 2025 pm 09:15 PM

The methods to correctly handle this pointing in JavaScript closures include: 1. Use arrow functions, 2. Use bind methods, 3. Use variables to save this. These methods ensure that this intrinsic function correctly points to the context of the external function.

How to implement data encryption with JavaScript? How to implement data encryption with JavaScript? May 23, 2025 pm 11:12 PM

Using JavaScript to implement data encryption can use the Crypto-JS library. 1. Install and introduce the Crypto-JS library. 2. Use the AES algorithm for encryption and decryption to ensure that the same key is used. 3. Pay attention to the secure storage and transmission of keys. It is recommended to use CBC mode and environment variables to store keys. 4. Consider using WebWorkers when you need high performance. 5. When processing non-ASCII characters, you need to specify the encoding method.

Detailed steps to deploy a Joomla website on PhpStudy Detailed steps to deploy a Joomla website on PhpStudy May 16, 2025 pm 08:00 PM

The steps to deploy a Joomla website on PhpStudy include: 1) Configure PhpStudy, ensure that Apache and MySQL services run and check PHP version compatibility; 2) Download and decompress PhpStudy's website from the official Joomla website, and then complete the installation through the browser according to the installation wizard; 3) Make basic configurations, such as setting the website name and adding content.

How to define constructors in PHP? How to define constructors in PHP? May 23, 2025 pm 08:27 PM

In PHP, the constructor is defined by the \_\_construct magic method. 1) Define the \_\_construct method in the class, which will be automatically called when the object is instantiated and is used to initialize the object properties. 2) The constructor can accept any number of parameters and flexibly initialize the object. 3) When defining a constructor in a subclass, you need to call parent::\_\_construct() to ensure that the parent class constructor executes. 4) Through optional parameters and conditions judgment, the constructor can simulate the overload effect. 5) The constructor should be concise and only necessary initialization should be done to avoid complex logic or I/O operations.

PHP Dependency Injection: Benefits and Examples PHP Dependency Injection: Benefits and Examples May 17, 2025 am 12:14 AM

The benefits of using dependency injection (DI) in PHP include: 1. Decoupling, making the code more modular; 2. Improve testability and easy to use Mocks or Stubs; 3. Increase flexibility and facilitate reusing of dependencies; 4. Improve reusability, and the classes can be used in different environments. By passing dependencies externally to objects, DI makes the code easier to maintain and extend.

Steps to change the root directory of PhpStudy website Steps to change the root directory of PhpStudy website May 16, 2025 pm 07:21 PM

To change the root directory of PhpStudy's website, you can use the following steps: 1. Find the httpd.conf file under the PhpStudy installation directory. 2. Modify the DocumentRoot directive to the new directory path. 3. Save the file and restart the Apache service. Advanced usage allows you to manage multiple root directories by setting up a virtual host. Pay attention to checking the path and permissions to ensure that Apache restarts successfully.

See all articles