Correcting teacher:PHPz
Correction status:qualified
Teacher's comments:
<?php
// 单例模式连接数据库
interface iDbBase
{
//数据库操作 curd
static function insert($db,$data);
static function select($db,$where=[]);
static function delete($db,$where=[]);
static function update($db,$data,$where=[]);
static function doConnect($dsn,$username,$password);
}
abstract class aDb implements iDbBase
{
// 创建类的唯一实例 pdo对象
private static $_instance;
// private私有的 阻止此类在外部进行实例化
private function __construct()
{
}
// private私有的 阻止此类在外部进行克隆
private function __clone()
{
}
static function doConnect($dsn,$username,$password)
{
// 得到pdo连接对象 储存在 $_instance
if(is_null(self::$_instance))
{
self::$_instance = new PDO($dsn,$username,$password);
}
return self::$_instance;
}
}
// 工作类
class Db extends aDb{
//数据库操作 curd
static function insert($db,$data=''){
return $db->query("INSERT INTO t_user ( name, type)VALUES('张杰','1')")->fetchAll(PDO::FETCH_ASSOC);
}
static function select($db,$where=['type'=>1]){
// select filed.. form tableName where gender=1 and id>1
// select filed.. form tableName where gender=1
$str = '';
foreach($where as $k=>$v)
{
if(is_array($where))
{
if(count($where) > 1)
{
$str .= $k . ' = ' . $v . ' and ';
}else{
$str .= $k . '=' . $v;
}
}
}
if(count($where) > 1)
{
// 去掉where中的最后一个and
$str = substr($str,0,strlen($str)-4);
// echo $str;
}
return $db->query("SELECT * FROM `t_user` WHERE $str ")->fetchAll(PDO::FETCH_ASSOC);
}
static function delete($db,$where=['id'=>4]){
$str = '';
foreach($where as $k=>$v)
{
if(is_array($where))
{
if(count($where) > 1)
{
$str .= $k . ' = ' . $v . ' and ';
}else{
$str .= $k . '=' . $v;
}
}
}
if(count($where) > 1)
{
// 去掉where中的最后一个and
$str = substr($str,0,strlen($str)-4);
// echo $str;
}
return $db->query("DELETE FROM t_user WHERE $str")->fetchAll(PDO::FETCH_ASSOC);
}
static function update($db,$data=2,$where=['name'=>'周杰伦','type'=>2]){
$str = '';
foreach($where as $k=>$v)
{
if(is_array($where))
{
if(count($where) > 1)
{
$str .= $k . ' = ' . '\'' . $v . '\''. ' , ';
}else{
$str .= $k . '=' . $v;
}
}
}
if(count($where) > 1)
{
// 去掉where中的最后一个and
$str = substr($str,0,strlen($str)-2);
echo $str;
}
return $db->query("UPDATE t_user SET $str WHERE id = '$data'")->fetchAll(PDO::FETCH_ASSOC);
}
}
// 客户端代码
$dsn = 'mysql:host=localhost;dbname=test_db';
$db = Db::doConnect($dsn,'test_db','123456');
//var_dump($db);
//print_r(Db::select($db));
//print_r(Db::insert($db));
//print_r(Db::delete($db));
print_r(Db::update($db));