Correcting teacher:天蓬老师
Correction status:qualified
Teacher's comments:写的很有意思
首先来看下我们的商品信息表的内容
接下来我们要使用mysqli方式完成对这张商品信息表的增删改查操作
1.配置参数:在根目录下创建文件/config/database.php,输入以下代码
namespace pdo_goods;
return[
'type' => $type ?? 'mysql',
'host' => $host ?? 'localhost',
'dbname' => $dbname ?? 'goods',
'charset' => $charset ?? 'utf8',
'port' => $port ?? '3306',
'username' => $username ?? 'root',
'password' => $password ?? 'root',
];
2.加载外部的数据库连接参数:在根目录下创建文件connect.php输入以下代码
namespace mysqli_goods;
use mysqli;
$config = require __DIR__ . '/config/database.php';
extract($config);
$mysqli = new mysqli($host, $username, $password ,$dbname);
if ($mysqli->connect_errno) echo $mysqli->connect_error;
$mysqli->set_charset($charset);
//单条查询
require 'connect.php';
$sql = "SELECT `id`, `name`, `standard` FROM `staffs` WHERE `price`>20";
$mysqli_result = $mysqli->query($sql);
if ($mysqli_result && $mysqli_result) {
while ($staff = $mysqli_result->fetch_assoc()) {
printf('<pre>%s</pre>', print_r($staff, true));
}
} else {
echo '查询失败或没有查询到满足条件的商品';
}
$mysqli_result->free_result();
$mysqli->close();
输出效果:
//多条查询
require 'connect.php';
$sql = "SELECT `id`, `name`, `standard` FROM `staffs` WHERE `price`>20";
$mysqli_result = $mysqli->query($sql);
if ($mysqli_result && $mysqli_result->num_rows > 0){
$staffs = $mysqli_result->fetch_all();
foreach($staffs as $staff){
vprintf('<li>编号:%s, 名称:%s, 规格:%s</li>',$staff);
}
// printf('<pre>%s</pre>',print_r($staff,true));
}else {
echo '查询失败或没有查询到满足条件的商品';
}
$mysqli_result->free_result();
$mysqli->close();
输出效果:
$arr = ['18524605265','哈哈果粒橙','350','6'];
array_walk($arr,function(&$item,$key) {
$item = "'$item'";
});
$data = implode(', ', $arr);
$sql = "INSERT `staffs`(`Number`, `name`, `model`, `price`) VALUES ($data)";
if($mysqli->query(($sql))) {
if ($mysqli->affected_rows > 0) {
echo '成功添加了' . $mysqli->affected_rows . '条记录,新增记录主键ID: ' . $mysqli->insert_id;
} else {
echo '没有添加新记录';
}
}else{
die('添加失败' . $mysqli->errno . ':' . $mysqli->error);
}
$mysqli->close();
输出效果:
require 'connect.php';
$arr = ['name'=>'哈哈锅巴','model'=>'240','price'=>5];
array_walk($arr, function(&$item, $key) {
$item = "`$key`='$item'";
});
$data = implode(', ', $arr);
$sql = "UPDATE `staffs` SET ". $data . " WHERE `id`=12";
if($mysqli->query($sql)) {
if ($mysqli->affected_rows > 0) {
echo '成功更新了' . $mysqli->affected_rows . '条记录';
} else {
echo '没有更新任何记录';
}
}else{
die('添加失败' . $mysqli->errno . ':' . $mysqli->error);
}
$mysqli->close();
输出效果:
require 'connect.php';
$sql = "DELETE FROM `staffs` WHERE `id`= 12";
if($mysqli->query($sql)) {
if ($mysqli->affected_rows > 0) {
echo '成功删除了 id=' . $mysqli->affected_rows . '条记录';
} else {
echo '没有删除任何记录';
}
}else{
die('删除失败' . $mysqli->errno . ':' . $mysqli->error);
}
$mysqli->close();
输出效果: