欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

insert,update,delete

程序员文章站 2024-01-10 09:28:58
...

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