博客列表 >insert,update,delete

insert,update,delete

木子木杉
木子木杉原创
2022年02月19日 15:04:19430浏览

<?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)

  1. {
  2. return $db->prepare("INSERT INTO `mj_user`(`uid`, `nickname`, `avatar`, `phone`, `password`, `status`
  3. , `log_num`, `add_time`, `add_ip`, `last_time`, `last_ip`, `role`) VALUES ('6','去无踪',
  4. '[value-3]','[value-4]','[value-5]','[value-6]','[value-7]','[value-8]','[value-9]','[value-10]',
  5. '[value-11]','[value-12]')")->execute();
  6. }
  7. static function select($db, $where = ['uid' => 1])
  8. {
  9. foreach ($where as $k => $v) {
  10. $sql = $k . '>' . $v;
  11. }
  12. return $db->query("SELECT * FROM `mj_user` WHERE " . $sql . " LIMIT 3")->fetchAll(PDO::FETCH_ASSOC);
  13. }
  14. static function update($db, $where = [])
  15. {
  16. return $db->prepare("UPDATE `mj_user` SET `nickname`='灭绝师妹' WHERE `uid`=?")->execute($where);
  17. }
  18. static function delete($db, $where = [])
  19. {
  20. return $db->prepare("DELETE FROM `mj_user` WHERE `uid`=?")->execute($where);
  21. }

}
//客户端代码
$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));

声明:本文内容转载自脚本之家,由网友自发贡献,版权归原作者所有,如您发现涉嫌抄袭侵权,请联系admin@php.cn 核实处理。
全部评论
文明上网理性发言,请遵守新闻评论服务协议