正在学习PHP OOP,写了一个数据库操作类,有问题,希望大牛们指点一下。

看小雪 2014-12-29 09:46:39
@xuzuning



<?php
/**
* 数据库PDO操作
* 注:使用此文件前,需要定义数据库的基本信息
* $dsn = 'mysql:host=127.0.0.1;port=3333;dbname=testdb', $username, $userpwd;
*/
class class_db {
private $statement = null; //PDOStatment

private $conn = null; //单件模式,保存Pdo类唯一实例,数据库的连接资源

public $lastSql = ''; //当前SQL语句

public $error = ''; //错误信息

private $lastInsertId = null; //最后插入记录的ID

private $numRows = 0; //返回影响记录数

public function __construct($dsn, $username, $userpwd){
if (!class_exists('PDO')) throw_exception("not support:PDO");

if(empty($dsn)) throw_exception("Please config DSN");

if(is_object($this->conn)) {
return $this->conn;
}

//$attrConfig = array('PDO::ATTR_PERSISTENT'=>true, 'PDO::ATTR_EMULATE_PREPARES'=>false,);
try {
$this->conn = new PDO($dsn, $username, $userpwd);
$this->conn->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
}catch(PDOException $e){
throw_exception($e->getMessage());
}

if(!$this->conn) throw_exception('PDO CONNECT ERROR');

$this->conn->exec('SET NAMES utf8');
$this->conn->exec('SET CHARACTER SET utf8');

return $this->conn;
}

//开始查询
public function query($sql)
{
if(empty($sql)){
return $this->error = 'empty sql!';
}
$this->lastSql = $sql;
try{
$this->statement = $this->conn->query($sql);
return $this->statement;
}catch(Exception $e){
$t = $this->conn->errorInfo();
$this->error = $t[2];
return false;
}
}

public function prepare($sql)
{
if(empty($sql)){
return $this->error = 'empty sql!';
}
$this->lastSql = $sql;
try{
$this->statement = $this->conn->prepare($sql);
return $this->statement;
}catch(Exception $e){
$t = $this->conn->errorInfo();
$this->error = $t[2];
return false;
}
}

//获取一条数据,返回一维数组
public function fetch()
{
try{
return $this->statement->fetch();
}catch(Exception $e){
$t = $this->conn->errorInfo();
$this->error = $t[2];
return false;
}
}

//获取多条数据,返回二维数组
public function fetchAll()
{
try{
return $this->statement->fetchAll();
}catch(Exception $e){
$t = $this->conn->errorInfo();
$this->error = $t[2];

return false;
}
}

//返回一个表字段内容
public function fetchColumn($intColumn = 0)
{
try{
return $this->statement->fetchColumn($intColumn);
}catch(Exception $e){
$t = $this->conn->errorInfo();
$this->error = $t[2];

return false;
}
}

//执行sql语句,主要用于无状态更新
public function exec($sql)
{
try{
$this->numRows = $this->conn->exec($sql);
return $this->numRows;
}catch(Exception $e){
$t = $this->conn->errorInfo();
$this->error = $t[2];

return false;
}
}

//插入数据后的ID
public function lastInsertId()
{
return $this->conn->lastInsertId();
}

//
public function execute($param = ""){
if(is_array($param)){
try{
return $this->statement->execute($param);
}catch (Exception $e){
$t = $this->conn->errorInfo();
$this->error = $t[2];
return false;
}
}
try{
return $this->statement->execute();
}catch(Exception $e){
$t = $this->conn->errorInfo();
$this->error = $t[2];
return false;
}
}

//受影响的行数
public function rowCount(){
return $this->numRows;
}

/*
$table 表名,string
$arrayData,字段与数据, 一维array
*/
public function insert($table, $arrayData){
if(empty($table) || !is_array($arrayData)){
$this->error = 'insert:data is not array or table is not exists!';
return false;
}
$vals = array_keys($arrayData);
$cols = array();
/*
$arrayobject = new ArrayObject( $arrayData );
$iterator = $arrayobject->getIterator();
while($iterator->valid()) {
$vals[] = ':' . $iterator->key() . '';
$iterator->next();
}
*/
$c = implode('', $vals);
$cols = array_filter(explode(':', $c));

$sql = "INSERT INTO {$table} (";
$sql .= implode(",", $cols) . ") VALUES (";
$sql .= implode(",", $vals) . ")";

$this->lastSql = $sql;
try{
$this->statement = $this->conn->prepare($sql);
$this->statement->execute($arrayData);
return $this->lastInsertId = $this->conn->lastInsertId();
}catch(Exception $e){
$t = $this->conn->errorInfo();
$this->error = $t[2];
return false;
}
}

/*
$table表名,string
$fields要更新的字段,string
$where 条件,string
*/
public function update($table, $fields, $where){
if(empty($table) || empty($fields) || empty($where)){
$this->error = 'update:data is not array!';
return false;
}

$sql = 'update '.$table.' set ' . $fields. ' where '. $where;

$this->lastSql = $sql;
try{
$this->statement = $this->conn->prepare($sql);
$this->statement->execute();
return $this->numRows = $this->statement->rowCount();
}catch(Exception $e){
$t = $this->conn->errorInfo();
$this->error = $t[2];
return false;
}
}

/*
$table表名,string
$where删除数据条件,一维array
*/
public function delete($table, $where){
if(empty($table) || empty($where) || !is_array($where)){
$this->error = 'delete:data is not array or table is not exists!';
return false;
}
$sql = 'delete from '.$table.' where ';

$cols = array();
$vals = array_keys($where);
$c = implode('', $vals);
$cols = array_filter(explode(':', $c));

$arr = array_combine($cols, $vals);
$i = 0;
$sql1 = '';
foreach($arr as $k => $v){
$t = ($i > 0) ? ' and ' : ' ';
$sql1 .= $t . ' ' . $k . '='. $v;
$i += 1;
}
$sql .= $sql1;

$this->lastSql = $sql;
try{
$this->statement = $this->conn->prepare($sql);
$this->statement->execute($where);
return $this->numRows = $this->statement->rowCount();
}catch(Exception $e){
$t = $this->conn->errorInfo();
$this->error = $t[2];
return false;
}
}
}
?>


版主,各位大牛,帮忙看看,这个类有缺点。类里面的fetch,fetchAll,fetchColumn没执行。


$db = new class_db('mysql:host=127.0.0.1;port=3306;dbname=test', 'root', '123456');

$sql = 'create table if not exists ttt (id int primary key auto_increment, title varchar(100), sort int)';
$db->exec($sql);
echo "<hr>";
echo '添加数据:'."<br>";
$data = array(':title'=>'山东红富士'.rand(1,100), ':sort'=>1);
$c = $db->insert('ttt', $data);
echo ($c > 0) ? "OK" : '添加数据失败',"<hr>";
if(empty($c))exit();

echo '获取一条数据:',"<br><pre>";
$sql = 'select * from ttt where id='.$c;
$rs = $db->query($sql)->fetch();
print_r($rs);
echo "<hr>";
exit;


我的意图在于组里所有的人都用此类,以后代码看起来统一一些,也能防止有些人偷懒,在添加数据的时候,拼接SQL语句,导致注入。目前似乎发现fetch,fetchAll,fetchColumn有问题,就是没执行,执行的是PDO的,不是我写的这个。
...全文
161 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
看小雪 2014-12-29
  • 打赏
  • 举报
回复
@xuzuning 我如果这样用是不是一个单例模式,访问效率是不是会比较的差? 希望更多的人指毛病,找问题。
xuzuning 2014-12-29
  • 打赏
  • 举报
回复
class_db::query 方法返回的是 PDOStatement 对象(54行 return $this->statement;) 所以 $rs = $db->query($sql)->fetch(); 这个是 PDOStatement 的方法 如果你需要是 class_db::fetch,那么 54 行处应 return $this;

21,893

社区成员

发帖
与我相关
我的任务
社区描述
从PHP安装配置,PHP入门,PHP基础到PHP应用
社区管理员
  • 基础编程社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧