: This article mainly introduces [my PHP journey] YII Framework learning 03 connecting to the database (using ActiveRecord). If you are interested in the PHP Tutorial, please refer to it. Prepare a data table at will
CREATETABLE`entry` ( `id`INT(11) NOTNULL AUTO_INCREMENT, `value`VARCHAR(12) NULLDEFAULTNULL, PRIMARYKEY (`id`))COLLATE='utf8_general_ci'ENGINE=InnoDBAUTO_INCREMENT=12;
Configure the Yii Database link
First, you must know that ActiveRecord is implemented using PDO_MySQ. therefore, make sure that your plug-in is easy to use. Then modifyFramework directory/config/db. php
As follows:
return [ 'class' => 'yii\db\Connection', 'dsn' => 'mysql:host=localhost;dbname=test', 'username' => 'root', 'password' => 'root', 'charset' => 'utf8',];
Create activity Record object (ActiveRecord)
namespaceapp\models;useyii\db\ActiveRecord;classEntryextendsActiveRecord {}
This class does not write anything. We use this class to tell Yii which table we want to extract data from.
Simple controller
namespaceapp\controllers;useyii\web\Controller;useapp\models\Entry;useyii\data\Pagination;classEntryControllerextendsController {publicfunctionactionGetAll() {$query = Entry::find(); $pagination = new Pagination([ 'defaultPageSize' => 5, 'totalCount' => $query->count(), ]); $entries = $query -> offset($pagination->offset) -> limit($pagination->limit) -> all(); return$this->render('showEntry', [ 'entries' => $entries, 'pagination' => $pagination, ]); } publicfunctionactionDelete() { Entry::deleteAll('value=\'***\''); returnself::actionGetAll(); }}
In the code, pagination is used for paging. if you do not need pagination, you can leave it empty. The delete function is not quite formal in writing...
Create View
Entries :
$pagination,]) ?>
In combination with LinkPager and Pagination, Yii is used to complete query and paging.
'). AddClass ('pre-numbering '). hide (); $ (this ). addClass ('Has-numbering '). parent (). append ($ numbering); for (I = 1; I <= lines; I ++) {$ numbering. append ($ ('
'). Text (I) ;}; $ numbering. fadeIn (1700) ;}) ;}; script
The above introduces [my PHP journey] YII Framework learning 03 connecting to the database (using ActiveRecord), including some content, and hope to help friends who are interested in PHP tutorials.