配置文件都在config目录中。数据库的配置文件是database.php
<?php
return [
'default' => 'mysql', //默认链接的名字
'connections' => [ //可以有多个连接
'mysql' => [
'driver' => 'PDO_MYSQL', // 'PDO_MYSQL' 驱动 'Wudimei\\DB\\Query\\PDO_MYSQL' 'your\\driver\\className'
'host' => 'localhost', //mysql的主机
'database' => 'wudimei_mvc', //数据库名称
'username' => 'root', //用户名
'password' => '123456', //密码
'charset' => 'utf8', //数据库字符编码
'collation' => 'utf8_unicode_ci',//数据库字符集
'prefix' => 'w_', //表前缀
'sql_error_display_method' => 'output', //数据库报错方式,可以填写为none
]
]
];
删除
<?php
$select = DB::connection( );
$intAffectedRows = $select->table("blog")->where('id',12)->orWhere('id',11)->orWhere('id',10)->delete( );
echo $intAffectedRows;
当然可以只删除一行
<?php
$intAffectedRows = DB::table("blog")->where('id',12)->delete( );
echo $intAffectedRows;
这里相当于产生一条sql语句:
delete from w_blog where id=12
这里是分组:
<?php
$data = DB::table("blog")->where('id','>',0)
->groupBy("title")->having("id", 1)->having("id", 1)
->get();
插入数据
<?php
$data = array(
'title' => 'ha ha ',
'content' => 'abc',
'created_at' => date("Y-m-d H:i:s")
);
$lastInsertId = DB::table("blog")->insert( $data );
echo $lastInsertId;
?>
从第一条后取出三行,用到limit()方法。
<?php
$data = DB::table("blog")->where('id','>',0)->orderBy("title","desc")
->orderBy('id','desc')->limit(3,1)->get();
使用数据库模型
<?php
use Wudimei\DB\Model;
class BlogModel extends Model{
public $table = "blog";
//public $primaryKey = "id";
}
$data = BlogModel::where("id",'>',0)->get();
$obj = BlogModel::find(1);
排序
<?php
$data = DB::table("blog")->where('id','>',0)->orderBy("title","desc")->orderBy('id','desc')->get();
快速分页
<?php
$pg = DB::table("blog")->where('id','>',1)->where('id','<',10)->paginate(2);
print_r( $pg->data );
echo $pg->render("db_paginate.php?page={page}");
数据更新
<?php
$data = array(
'title' => 'ha ha 2',
'content' => 'abc2',
'created_at' => date("Y-m-d H:i:s")
);
/*
$data = new stdClass();
$data->title = "hello";
*/
$intAffectedRows = DB::table("blog")->where('id',1 )->update( $data );
echo $intAffectedRows;
whereIn
<?php
$data = DB::table("blog")->whereIn('id',[1,2,3] )->orWhereIn('id',[6,7] )->get();
选取指定字段:
<?php
$data = DB::select('title,id')->table("blog")->get();
sql语句
<?php
$count = DB::table("blog")->whereRaw('title like ?',['test%'])->count('id');
统计函数:
<?php
$count = DB::table("blog")->whereRaw('title like ?',['test%'])->count('id');
$max = DB::table("blog")->max("id");
$min = DB::table("blog")->min("id");
$avg = DB::table("blog")->avg("id");
$sum = DB::table("blog")->where('id','>',0)->sum("id");
上面的get()方法是返回所有符合条件的数据。all()方法是它的别名。
<?php
$objArray = DB::table("blog")->all();
?>
只取出一条:
<?php
$obj = DB::table("blog")->where('id',1)->first();
?>