Correcting teacher:天蓬老师
Correction status:qualified
Teacher's comments:很不错的, 代码非常的清晰
CREATE DATABASE IF NOT EXISTS `test` CHARSET UTF8 COLLATE UTF8_GENERAL_CI;
CREATE TABLE IF NOT EXISTS `customers`
(
`cust_id` INT UNSIGNED PRIMARY KEY AUTO_INCREMENT,
`cust_name` CHAR(50) NOT NULL,
`cust_sex` CHAR(1) NOT NULL DEFAULT 0,
`cust_address` CHAR(50),
`cust_contact` CHAR(50)
) ENGINE INNODB
CHARSET UTF8
COLLATE UTF8_GENERAL_CI;
<?php
namespace config;
return [
//数据库类型
'type' => $type ?? 'mysql',//相当于isset($type)?$type:'localhost'
//主机
'host' => $host ?? 'localhost',
//默认数据库
'dbname' => $dbname ?? 'php11',
//用户名
'username' => $username ?? 'root',
//密码
'password' => $password ?? 'root',
//端口
'port' => $port ?? 3306,
//默认字符集
'charset' => $charset ?? 'UTF8'
];
<?php
namespace connect;
use PDO;
use Exception;
//引入数据库配置文件
$config = require_once './config/config.php';
//获取数据库配置
$type = $config['type'];
$host = $config['host'];
$dbname = $config['dbname'];
$username = $config['username'];
$password = $config['password'];
//数据源
$dsn = $type . ':' . 'host=' . $host . ';dbname=' . $dbname;
//连接数据库
try {
$pdo = new PDO($dsn, $username, $password);
echo '数据库连接成功<br>';
} catch (Exception $e) {
echo $e->getMessage();
}
<?php
namespace delete;
//引入数据库连接文件
require_once './connect.php';
//SQL
$sql = "INSERT INTO `customers` VALUES (null, ?, ?, ?, ?);";
//预处理语句
$stmt = $pdo->prepare($sql);
//数据
$data = ['张三', 0, '黑龙江省哈尔滨市', 18888888888];
//参数绑定(按位置进行依次绑定),并执行SQL
$stmt->execute($data);
//是否执行成功
if ($stmt->rowCount() > 0) {
echo '数据新增成功,最后一条插入的ID为:' . $pdo->lastInsertId();
} else {
echo '数据新增失败,错误信息为:';
print_r($stmt->errorInfo());
}
<?php
namespace delete;
//引入数据库连接文件
require_once './connect.php';
//SQL
$sql = "DELETE FROM `customers` WHERE `cust_id` = :cust_id;";
//预处理语句
$stmt = $pdo->prepare($sql);
//数据
$data = [':cust_id'=>1];
//参数绑定(按名称进行绑定),并执行SQL
$stmt->execute($data);
//是否执行成功
if ($stmt->rowCount() > 0) {
echo '数据删除成功';
} else {
echo '数据删除失败,错误信息为:';
print_r($stmt->errorInfo());
}
<?php
namespace delete;
//引入数据库连接文件
require_once './connect.php';
//SQL
$sql = "UPDATE `customers` SET `cust_address` = :cust_address WHERE `cust_id` = :cust_id;";
//预处理语句
$stmt = $pdo->prepare($sql);
//数据
$data = [
':cust_address' => '北京市',
':cust_id' => 6
];
//参数绑定(按名称进行绑定),并执行SQL
$stmt->execute($data);
//是否执行成功
if ($stmt->rowCount() > 0) {
echo '数据更新成功';
} else {
echo '数据更新失败,错误信息为:';
print_r($stmt->errorInfo());
}