欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Yii2框架操作数据库的方法分析【以mysql为例】

程序员文章站 2022-06-23 21:42:18
本文实例讲述了yii2框架操作数据库的方法。分享给大家供大家参考,具体如下: 准备数据库 drop table if exists `pre_user`; c...

本文实例讲述了yii2框架操作数据库的方法。分享给大家供大家参考,具体如下:

准备数据库

drop table if exists `pre_user`;
create table `pre_user`(
  `id` int(11) auto_increment primary key,
  `username` varchar(255) not null,
  `password` varchar(32) not null default '',
  `password_hash` varchar(255) not null default '',
  `email` varchar(255) not null default '',
  `status` smallint(6) not null default 10,
  `created_at` smallint(6) not null default 0,
  `updated_at` smallint(6) not null default 0
)engine=innodb default charset=utf8mb4;

配置连接

config\db.php

<?php
return [
  'class' => 'yii\db\connection',
  'dsn' => 'mysql:host=localhost;dbname=yii2',
  'username' => 'root',
  'password' => 'root',
  'charset' => 'utf8mb4',
  'tableprefix' => 'pre_'
];

查看数据库连接是否成功

控制器里打印:

var_dump(\yii::$app->db);

Yii2框架操作数据库的方法分析【以mysql为例】

怎么执行sql语句?

增删改

// 接收表单的数据
$username = 'jack';
$sql = "insert into {{%user}} (username,status) values (:username,:status)";
// 返回受影响行数
$row = \yii::$app->db->createcommand($sql,['username'=>$username,'status'=>8])->execute();
// 获取自增id
echo \yii::$app->db->getlastinsertid();

查询

$sql = "select * from {{%user}} where id>:id";
// 查询结果是一个二维数组
$userarr = \yii::$app->db->createcommand($sql,['id'=>1])->queryall();
// 如果要查询一个
$user = \yii::$app->db->createcommand($sql,['id'=>1])->queryone();
// 如果要返回单值
// 例如 select count(*)语句
$count = \yii::$app->db->createcommand($sql,['id'=>1])->queryscalar();
echo $count;

更多关于yii相关内容感兴趣的读者可查看本站专题:《yii框架入门及常用技巧总结》、《php优秀开发框架总结》、《smarty模板入门基础教程》、《php面向对象程序设计入门教程》、《php字符串(string)用法总结》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总

希望本文所述对大家基于yii框架的php程序设计有所帮助。