抽象理解透彻:update , delete, insert, Select操作
案例效果:
案例源码:
一、定义接口:
interface jkDbBase
{
//数据库插入操作
static function insert($db,$data);
//数据库查询操作
static function select($db,$options=[]);
//数据库删除操作
static function delete($db,$where);
// 数据库更新操作
static function update($db,$options=[]);
}
二、定义中间类/抽象类:
abstract class jkDb implements JKDbBase {
protected static $db = null;
public static function connect($dsn,$username,$password)
{
// 判断是否连接数据库
if(is_null(self::$db)){
self::$db = new PDO($dsn,$username,$password);
}
return self::$db;
}
}
三、工作类,数据库CURD操作
class DB extends jkDb
{
// 数据插入
static function insert($db,$data)
{
$sql = 'INSERT `user` SET `uname`=?,`pwd`=?,`age`=?;';
$stmt = $db->prepare($sql);
$stmt -> execute($data);
return $stmt;
}
// 数据查询
static function select($db,$options=[]){
return $db->query('SELECT * FROM `user` LIMIT 2')->fetchAll(PDO::FETCH_ASSOC);
}
// 数据删除
static function delete($db,$where){
$sql3 = 'DELETE FROM `user` WHERE `id`= ?;';
$stmt3 = $db->prepare($sql3);
$stmt3 -> execute([8]);
return $stmt3;
}
// 数据更新
static function update($db,$data4=[])
{
$sql4 = 'UPDATE `user` SET `uname` = ?,`pwd`=?,`age`=? WHERE `id`=?;';
$stmt4 = $db->prepare($sql4);
$stmt4 ->execute($data4);
return $stmt4;
}
}
四、数据库配置
$config = [
'type' => $type ?? 'mysql',
'host' => $host ?? 'localhost',
'dbname' => $dbname??'study',
'username' => $username ?? 'root',
'password' => $password ?? '123456',
];
五、PDO数据连接数据库
$dsn = sprintf('%s:host=%s;dbname=%s;',$config['type'],$config['host'],$config['dbname']);
$username = $config['username'];
$password = $config['password'];
$db = DB::connect($dsn,$username,$password);
// 设置错误级别
$db->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_WARNING);
六、数据输出
// 1、插入数据
$data = ['二狗',md5('123456'),26];
$stmt = DB::insert($db,$data);
if($stmt->rowCount() > 0) echo '插入成功' . $stmt->rowCount() . '条记录,新增数据的id为:' . $db->lastInsertId();
// 输出:插入成功1条记录,新增数据的id为:7
echo "<hr>";
// 2、查询数据
foreach ((DB::select($db))as $user)
{
print_r($user);
}
// 输出:Array ( [id] => 1 [uname] => admin [pwd] => e10adc3949ba59abbe56e057f20f883e [age] => 20 ) Array ( [id] => 2 [uname] => fugen [pwd] => e10adc3949ba59abbe56e057f20f883e [age] => 30 )
echo "<hr>";
// 3、删除数据
$stmt3 = DB::delete($db,$stmt3);
if($stmt3->rowCount() > 0) echo '删除成功' . $stmt3->rowCount() . '条记录';
// 输出:删除成功1条记录
echo "<hr>";
// 4、更新数据
$data4 = ['毛毛',md5('123456'),52,6];
$stmt4 = DB::update($db,$data4);
if($stmt4->rowCount() > 0) echo '更新成功' . $stmt4->rowCount() . '条记录';
// 输出:更新成功1条记录
案例总结:
OOP知识:
- interface,接口是特殊的抽象类,接口是定义,类是实现;
- 抽象类:设计与实现分离,抽象类为子类定义公共接口,具体实现交由子类完成;
PDO知识:
- PDO数据连接~三要素 DSN数据源 username password;
- prepare() — 准备要执行的语句,并返回语句对象 object(PDOStatement);
- PDOStatement::execute — 执行一条预处理语句;
- sql查询 “SELECT * FROM user WHERE id=1”;
- sql删除 DELETE FROM TABLE_NAME WHERE CLAUSE;
- sql插入 insert into table_name (column_name)values();
- sql更新 UPDATE table_name SET column_name=new_value,…[WHERE Clause];