本文实例讲述了yii2.0框架数据库操作。分享给大家供大家参考,具体如下:
添加
1
2
3
4
5
6
7
8
9
10
11
|
$id = \Yii:: $app ->db
->createCommand()
->insert( '表名' ,[ 'car_num' => $car_num , 'lg_shop_id' => $shop_id ])
->execute();
batchInsert():一次添加多行
// table name, column names, column values
Yii:: $app ->db->createCommand()->batchInsert( 'user' , [ 'name' , 'age' ], [
[ 'Tom' , 30],
[ 'Jane' , 20],
[ 'Linda' , 25],
])->execute();
|
修改
1
2
|
// UPDATE (table name, column values, condition)
Yii:: $app ->db->createCommand()->update( 'user' , [ 'status' => 1], 'age > 30' )->execute();
|
删除
1
2
|
// DELETE (table name, condition)
Yii:: $app ->db->createCommand()-> delete ( 'user' , 'status = 0' )->execute();
|
查询条件
1
2
3
4
5
6
|
$status = 10;
$search = 'yii' ;
$query ->where([ 'status' => $status ]);
if (! empty ( $search )) {
$query ->andWhere([ 'like' , 'title' , $search ]);
}
|
如果 $search 不为空,那么将会生成如下 SQL 语句:
1
|
... WHERE (`status` = 10) AND (`title` LIKE '%yii%' )
|
查询以及打印查询sql
1
2
3
4
5
6
7
8
|
$query = new Query();
$query ->from( '{{%shop_info}}' );
$query ->where( 'shop_type=1' );
$query ->select( 'shop_name' );
$rea = $query ->all(); //查询
$res = $query ->createCommand(); //打印sql
echo $res ->sql; die ;
var_dump( $rea ); die ;
|
希望本文所述对大家基于Yii框架的PHP程序设计有所帮助。
原文链接:https://blog.csdn.net/qq_42176520/article/details/100514429