Correcting teacher:PHPz
Correction status:qualified
Teacher's comments:
作业标题:0813 oop编程-3
作业内容:参考demo3.php, 完善数据库查询构造器其他的操作,update,delete,insert
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($data);
}
static function select($db,$where=['empno'=>7369]){
// 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;
}
echo $str;
// SELECT `uname`, `tel` FROM `iuser` WHERE gender = 1 and id = 20201
return $db->query("SELECT `ename`, `job` FROM `emp` WHERE $str ")->fetchAll(PDO::FETCH_ASSOC);
}
static function delete($db,$where=['empno'=>7936]){
//DELETE FROM Persons WHERE LastName='Griffin'
$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;
}
echo $str;
// DELETE FROM Persons WHERE LastName='Griffin'
return $db->query("DELETE FROM `emp` WHERE $str ")->fetchAll(PDO::FETCH_ASSOC);
}
static function update($db,$data=1000,$where=['empno'=>7938]){
$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;
}
echo $str;
// UPDATE Persons SET Age=36 WHERE FirstName='Peter' AND LastName='Griffin'
return $db->query("UPDATE `emp` SET salary=$data WHERE $str ");
}
}
$dsn = 'mysql:host=localhost;dbname=my_test';
$db = Db::doConnect($dsn,'root','root');
$data="INSERT INTO emp "."(empno,ename,job,mgr,hiredate,salary,comm,deptno)"."VALUES"."('7938','张同','职员','7900','2012-08-07',3000,400,30)";
print_r(Db::select($db));
print_r(Db::insert($db,$data));
print_r(Db::delete($db));
print_r(Db::update($db));