用户表增删改查小案例
1.1 index.php
<?php
namespace pdo_edu;
use MyPDO;
//自动加载类
spl_autoload_register(function ($class_name) {
require "./{$class_name}.class.php";
});
//连接数据库
$config = require 'config/database.php';
$mypdo = MyPDO::getInstance($config);
//获取用户数据
$list = $mypdo->fetchAll('select * from data_user');
//渲染视图
require './data_user_list.html';
//进行编辑操作
//获取编辑时提交的数据
@$username = trim($_POST['user_name']);
@$password = trim($_POST['user_pass']);
@$id = array_flip($_POST);
@$id = $id['编辑'];
if ($_POST) {
$sql = "UPDATE `data_user` SET `user_name` = '{$username}',`user_pass`='{$password}' WHERE `user_id`={$id}";
$update = $mypdo->exec($sql);
}
//添加用户
$booladd = $_GET['add_user'] ?? 0;
if ($booladd) {
$addname = time();
$sql = "INSERT `data_user` SET `user_name` = '{$addname}',`user_pass`='0000' ";
$insert = $mypdo->exec($sql);
}
//删除用户
$booldel = $_GET['del'] ?? 0;
if ($booldel) {
$sql = "DELETE FROM `data_user` WHERE `user_id`={$booldel}";
$del = $mypdo->exec($sql);
}
1.2 data_user_list.html 渲染视图
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>用户管理</title>
</head>
<body>
<a href="?">刷新当前页</a>
<a href="?add_user=1">添加用户</a>
<table border='1' width='980' bordercolor='#000'>
<tr>
<th>用户ID</th>
<th>用户名</th>
<th>用户密码</th>
<th>操作</th>
</tr>
<?php foreach($list as $rows):?>
<form action="?" method="post">
<tr>
<td>
<?=$rows['user_id']?>
</td>
<td>
<input type="text" name="user_name" value=" <?=$rows['user_name']?>">
</td>
<td>
<input type="text" name="user_pass" value=" <?=$rows['user_pass']?>">
</td>
<td><input type="submit" value="编辑" name="<?=$rows['user_id']?>"><span>-----</span><a href="?del=<?=$rows['user_id']?>">删除</a></td>
</tr>
</form>
<?php endforeach;?>
</table>
</body>
</html>
1.3 MyPDO.class.php 自定义PDO
<?php
class MyPDO {
private $type; //数据库类别
private $host; //主机地址
private $port; //端口号
private $dbname; //数据库名
private $charset; //字符集
private $user; //用户名
private $pwd; //密码
private $pdo; //保存PDO对象
private static $instance;
private function __construct($param) {
$this->initParam($param);
$this->initPDO();
$this->initException();
}
private function __clone() {
}
public static function getInstance($param=array()){
if(!self::$instance instanceof self)
self::$instance=new self($param);
return self::$instance;
}
//初始化参数
private function initParam($param){
$this->type=$param['type']??'mysql';
$this->host=$param['host']??'127.0.0.1';
$this->port=$param['port']??'3306';
$this->dbname=$param['dbname']??'data';
$this->charset=$param['charset']??'utf8';
$this->user=$param['user']??'root';
$this->pwd=$param['pwd']??'root';
}
//初始化PDO
private function initPDO(){
try{
$dsn="{$this->type}:host={$this->host};port={$this->port};dbname={$this->dbname};charset={$this->charset}";
$this->pdo=new PDO($dsn, $this->user, $this->pwd);
} catch (PDOException $ex) {
$this->showException($ex);
exit;
}
}
//显示异常
private function showException($ex,$sql=''){
if($sql!=''){
echo 'SQL语句执行失败<br>';
echo '错误的SQL语句是:'.$sql,'<br>';
}
echo '错误编号:'.$ex->getCode(),'<br>';
echo '错误行号:'.$ex->getLine(),'<br>';
echo '错误文件:'.$ex->getFile(),'<br>';
echo '错误信息:'.$ex->getMessage(),'<br>';
}
//设置异常模式
private function initException(){
$this->pdo->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
}
//执行增、删、改操作
public function exec($sql){
try{
return $this->pdo->exec($sql);
} catch (PDOException $ex) {
$this->showException($ex, $sql);
exit;
}
}
//获取自动增长的编号
public function lastInsertId(){
return $this->pdo->lastInsertId();
}
//判断匹配的类型
private function fetchType($type){
switch ($type){
case 'num':
return PDO::FETCH_NUM;
case 'both':
return PDO::FETCH_BOTH;
case 'obj':
return PDO::FETCH_OBJ;
default:
return PDO::FETCH_ASSOC;
}
}
//获取所有数据 ,返回二维数组
public function fetchAll($sql,$type='assoc'){
try{
$stmt=$this->pdo->query($sql); //获取PDOStatement对象
$type= $this->fetchType($type); //获取匹配方法
return $stmt->fetchAll($type);
} catch (Exception $ex) {
$this->showException($ex, $sql);
}
}
//获取一维数组
public function fetchRow($sql,$type='assoc'){
try{
$stmt=$this->pdo->query($sql); //获取PDOStatement对象
$type= $this->fetchType($type); //获取匹配方法
return $stmt->fetch($type);
} catch (Exception $ex) {
$this->showException($ex, $sql);
exit;
}
}
//返回一行一列
public function fetchColumn($sql){
try{
$stmt=$this->pdo->query($sql);
return $stmt->fetchColumn();
} catch (Exception $ex) {
$this->showException($ex, $sql);
exit;
}
}
}
3.4 创建config配置文件夹 写入 database.php 数据库配置文件
<?php
namespace pdo_edu;
// 数据库连接配置参数
return [
// 数据库的类型
'type' => $type ?? 'mysql',
// 数据库默认主机
'host' => $host?? 'localhost',
// 默认数据库
'dbname'=> $dbname ?? 'phpedu',
// 默认字符编码集
'charset'=> $charset ?? 'utf8',
// 默认端口号
'port'=> $port ?? '3306',
// 默认的用户名
'user'=> $username ?? 'root',
// 默认的用户密码
'pwd'=> $password ?? 'root',
];
效果图:
增: