Correcting teacher:天蓬老师
Correction status:qualified
Teacher's comments:相当棒, 一个优秀的图文教程, 语句也很规范
建立一个mysqli查询类,使用内部方法完成增删改查数据库.
<?php
$config = [
'host' => 'localhost',
'username' => 'root',
'password' => 'root',
'dbname' => 'phpedu'
];
//创建一个mysqli查询类
class db
{
private $mysqli;
public function __construct($content)
{
extract($content);
$this->mysqli = new mysqli($host, $username, $password, $dbname);
return $this;
}
//查询商品价格
public function select($name, &$price = null)
{
$sql = "SELECT `price` FROM products WHERE `name`='$name'";
$sql_obj = $this->mysqli->query($sql);
$price = $sql_obj->fetch_assoc()['price'];
if ($price === null) :
return false;
else :
return true;
endif;
}
//增加一个商品
public function insert($name, $price, &$id = null)
{
$sql = "INSERT `products` SET `name`='$name',`price`=$price";
$sql_obj = $this->mysqli->query($sql);
$id = $this->mysqli->insert_id;
if ($id === 0) :
return false;
else :
return true;
endif;
}
//修改一个商品的价格
public function update($name, $price, &$result)
{
$sql = "UPDATE `products` SET `price`=$price WHERE `name`='$name'";
$this->mysqli->query($sql);
$result = $this->mysqli->affected_rows;
if ($result === 0) :
return false;
else :
$result = $price;
return true;
endif;
}
//删除一个商品
public function delete($name)
{
$sql = "DELETE FROM `products` WHERE `name`='$name'";
$this->mysqli->query($sql);
$result = $this->mysqli->affected_rows;
if ($result === 0) :
return false;
else :
return true;
endif;
}
}
//建立查询对象
$db = new db($config);
//查询商品价格
if ($db->select('真维斯', $price)) :
echo '真维斯:' . $price . '<hr>';
else :
echo '查询的商品信息不存在<hr>';
endif;
// //录入商品
if ($db->insert('李宁', '525', $id)) :
echo '录入商品成功!商品ID为:' . $id . '<hr>';
else :
echo '录入失败!<hr>';
endif;
//修改商品价格
$name = '真维斯';
if ($db->update($name, '356', $price)) :
echo '已将' . $name . '的价格修改为' . $price . '<hr>';
else :
echo '修改商品失败<hr>';
endif;
// //删除商品
if ($db->delete('联想')) :
echo '删除成功<hr>';
else :
echo '删除失败<hr>';
endif;