CakePHP的使用數(shù)據(jù)庫

2018-01-14 19:25 更新

在CakePHP中使用數(shù)據(jù)庫是很容易的。我們將在本章節(jié)了解CRUD(創(chuàng)建,讀取,更新,刪除)操作。在開始之前,我們需要在數(shù)據(jù)庫中創(chuàng)建以下users表。

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

此外,我們還需要在config/app.php文件中配置數(shù)據(jù)庫。

插入一條記錄

要在數(shù)據(jù)庫中插入一條記錄,首先,我們需要使用TableRegistry類獲得一個表(table)。我們可以用TableRegistry類的get()方法獲取表的實(shí)例。get()方法將表名作為參數(shù)。

用get()方法取得的實(shí)例創(chuàng)建實(shí)體。為實(shí)體設(shè)置必要的值。然后,調(diào)用該實(shí)例的save()方法在數(shù)據(jù)庫中插入記錄。

在以下項(xiàng)目中修改config/routes.php。

config/routes.php文件

<?php
   use CakeCorePlugin;
   use CakeRoutingRouteBuilder;
   use CakeRoutingRouter;

   Router::defaultRouteClass('DashedRoute');
   Router::scope('/', function (RouteBuilder $routes) {
      $routes->connect('/users/add', ['controller' => 'Users', 'action' => 'add']);
      $routes->fallbacks('DashedRoute');
   });
   Plugin::routes();

src/Controller/目錄下創(chuàng)建一個UsersController.php文件。復(fù)制以下代碼至其中。

src/Controller/UsersController.php

<?php
   namespace AppController;
   use AppControllerAppController;
   use CakeORMTableRegistry;
   use CakeDatasourceConnectionManager;
   use CakeAuthDefaultPasswordHasher;

   class UsersController extends AppController{
      public function add(){
         if($this->request->is('post')){
            $username = $this->request->data('username');
            $hashPswdObj = new DefaultPasswordHasher;
            $password = $hashPswdObj->hash($this->request->data('password'));
            $users_table = TableRegistry::get('users');
            $users = $users_table->newEntity();
            $users->username = $username;
            $users->password = $password;
         
            if($users_table->save($users))
            echo "User is added.";
         }
      }
   }
?>

在src/Template目錄下創(chuàng)建一個Users目錄下,并在Users目錄下創(chuàng)建一個名為add.ctp的視圖文件。復(fù)制以下代碼至其中。

src/Template/Users/add.ctp

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

通過訪問以下網(wǎng)址執(zhí)行上面的例子。

http://localhost:85/CakePHP/users/add

輸出

執(zhí)行以上程序,您會看到如下頁面。



以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號