Correcting teacher:天蓬老师
Correction status:qualified
Teacher's comments:你可能会觉得mysqli比较麻烦, 其实这才是最规范的操作步骤, 不是吗?
namespace mysql_edu;
use mysqli;
$config = require __DIR__ . '/databases.php';
//检测是否是个合法的数组
//print_r(extract($config));
extract($config);
//$mysqli = new mysqli($host,$username,$password,$dbname);
$mysqli = new mysqli($host,$username,$password,$dbname);
//print_r($mysqli);
if ($mysqli->connect_errno)echo $mysqli->connect_error;
//设置mysql的字符集
$mysqli->set_charset($charset);
namespace mysql_edu;
require 'connect.php';
$arr='刘云111';
//多条添加
//array_walk($arr, function(&$item, $key, $length) {
// if ($key < $length-1 ) $item = "'$item'";
//}, count($arr));
//
//echo $data = implode(', ', $arr);die();
//$sql = "INSERT `staff` (`name`) VALUES ($arr)";
$sql = "INSERT `staff` (`name`) VALUES ('$arr')";
//echo $sql;die();
//$sql = "INSERT `staffs` (`name`,`age`,`sex`,`position`,`mobile`,`hiredate`) 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();
namespace mysql_edu;
require 'connect.php';
$sql = "SELECT `name` FROM `staff`";
//echo $sql;
$mysqli_result = $mysqli->query($sql);
// 指针复位
$mysqli_result->data_seek(0);
if ($mysqli_result && $mysqli_result->num_rows > 0 ) {
while ($staff = $mysqli_result->fetch_assoc()) {
printf('<pre>%s</pre>', print_r($staff, true));
}
} else {
echo '查询失败';
}
//$mysqli_result->free_result();
$mysqli->close();
namespace mysql_edu;
require 'connect.php';
$sql = "SELECT `name` FROM `staff`";
//echo $sql;
$mysqli_result = $mysqli->query($sql);
if ($mysqli_result && $mysqli_result->num_rows > 0 ) {
$staffs = $mysqli_result->fetch_all();
foreach ($staffs as $staff) {
// vprintf() 与 printf()功能一样, 区别 就是参数是数组
vprintf('<li> 姓名: %s</li>', $staff);
}
} else {
echo '查询失败或没有查询到满足条件的员工';
}
//$mysqli_result->free_result();
$mysqli->close();
<?php
namespace pdo_edu;
require 'connect.php';
$arr=['name'=>'志佳'];
array_walk($arr, function(&$item, $key) {
$item = "`$key` = '$item'";
});
$data = implode(', ', $arr);
$sql= "UPDATE `staff` SET ". $data."WHERE `id` = 14";
if ($mysqli->query($sql)) {
if ($mysqli->affected_rows > 0) {
echo '成功更新了 ' . $mysqli->affected_rows . ' 条记录';
} else {
echo '没有更新任何记录';
}
} else {
die('更新失败'. $mysqli->errno . ' : ' . $mysqli->error);
}
$mysqli->close();
namespace mysql_edu;
require 'connect.php';
$sql="DELETE FROM `staff` WHERE `id`=".$_GET['id'];
if ($mysqli->query($sql)) {
if ($mysqli->affected_rows > 0) {
echo '成功删除了 id=' .$_GET['id'] . ' 的记录';
} else {
echo '没有删除任何记录';
}
} else {
die('删除失败'. $mysqli->errno . ' : ' . $mysqli->error);
}
// 3. 关闭连接
$mysqli->close();