<?php
namespace app\li;
use pdo;
//单例模式连接数据库 应用程序跟数据库交互
interface idbBase
{
//数据库连接 curd
static function insert($db);
static function select($db, $where = []);
static function update($db, $where = []);
static function delete($db, $where = []);
//数据库连接
static function doconnect($dsn, $username, $password);
}
//单例模式连接数据库
abstract class adb implements idbBase
{
private static $_instance;
private function construct()
{
}
private function clone()
{
}
static function doconnect($dsn, $user, $password)
{
//创建adb类唯一实例 获取唯一的pdo对象
if (is_null(self::$_instance)) {
self::$_instance = new pdo($dsn, $user, $password);
}
return self::$_instance;
}
}
//工作类
class DB extends adb
{
static function insert($db)
{
return $db->prepare("INSERT INTO `mj_user`(`uid`, `nickname`, `avatar`, `phone`, `password`, `status`
, `log_num`, `add_time`, `add_ip`, `last_time`, `last_ip`, `role`) VALUES ('6','去无踪',
'[value-3]','[value-4]','[value-5]','[value-6]','[value-7]','[value-8]','[value-9]','[value-10]',
'[value-11]','[value-12]')")->execute();
}
static function select($db, $where = ['uid' => 1])
{
foreach ($where as $k => $v) {
$sql = $k . '>' . $v;
}
return $db->query("SELECT * FROM `mj_user` WHERE " . $sql . " LIMIT 3")->fetchAll(PDO::FETCH_ASSOC);
}
static function update($db, $where = [])
{
return $db->prepare("UPDATE `mj_user` SET `nickname`='灭绝师妹' WHERE `uid`=?")->execute($where);
}
static function delete($db, $where = [])
{
return $db->prepare("DELETE FROM `mj_user` WHERE `uid`=?")->execute($where);
}
}
//客户端代码
$config = [
‘type’ => $type ?? ‘mysql’,
‘host’ => $host ?? ‘localhost’,
‘dbname’ => $dbname ?? ‘phpcn’,
‘username’ => $username ?? ‘root’,
‘password’ => $password ?? ‘’,
‘port’ => $port ?? ‘3306’,
‘charset’ => $charset ?? ‘utf8’
];
extract($config);
$dsn = sprintf(‘%s:host=%s;port=%s;charset=%s;dbname=%s’, $type, $host, $port, $charset, $dbname);
$pdo = DB::doconnect($dsn, $username, $password);
// var_dump(DB::select($pdo));
// var_dump(DB::delete($pdo, [4]));
// var_dump(DB::update($pdo, [3]));
var_dump(DB::insert($pdo));