随意准备一个数据表
createtable`entry` ( `id`int(11) notnull auto_increment, `value`varchar(12) nulldefaultnull, primarykey (`id`))collate='utf8_general_ci'engine=innodbauto_increment=12;
配置yii数据库链接
首先要知道activerecord是利用pdo_mysq来实现的,所以要确认自己的这个插件好用。 然后修改框架目录/config/db.php 如下:
return [ 'class' => 'yii\db\connection', 'dsn' => 'mysql:host=localhost;dbname=test', 'username' => 'root', 'password' => 'root', 'charset' => 'utf8',];
创建活动记录对象(activerecord)
namespaceapp\models;useyii\db\activerecord;classentryextendsactiverecord {}
这个类里面什么都不写,我们利用这个类告诉了yii我们要从哪一张表中提取出数据。
简单的控制器
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(); }}
代码中pagination是用来分页的,如果没有需求当然那可以不写。其中的删除函数写的好像不怎么正规。。。
创建视图
entries : = html::encode($entry->id : $entry->value) ?>= linkpager::widget([ 'pagination' => $pagination,]) ?>
结合linkpager与pagination,使用yii完成了查询与分页。
').addclass('pre-numbering').hide(); $(this).addclass('has-numbering').parent().append($numbering); for (i = 1; i ').text(i)); }; $numbering.fadein(1700); }); }); 以上就介绍了[我的php之旅] yii框架学习 03连接数据库(使用activerecord),包括了方面的内容,希望对php教程有兴趣的朋友有所帮助。
