PHP PDO操作
<?php/**
* DB驱动
*/
class DBLibrary
{
private $obj;
/**
*
* @Param $host [连接地址]
* @param $name [数据库名]
* @param $user [用户名]
* @param $pwd [用户密码]
* @param $connect [是否长连接]
*/
private function __construct($host, $name, $user, $pwd, $connect)
{
if(empty($host) || empty($name) || empty($user) || empty($pwd)) exit('Param Error');
try
{
$charset = C('charset');
$charset = empty($charset) ? 'utf8' : str_replace('-', '', $charset);
@$this->obj = new PDO("mysql:dbname={$name};host={$host};charset={$charset}", $user, $pwd, array(PDO::ATTR_PERSISTENT=>$connect));
/* 属性设置 */
$this->obj->setAttribute(PDO::ATTR_CASE, PDO::CASE_NATURAL);
}
catch(PDOException $e)
{
exit('DB Connect Fails');
}
}
/**
*
* @param string $type [请求类型]
*/
public static function SetInstance($host, $name, $user, $pwd, $connect = false)
{
static $object = null;
if(!is_object($object)) $object = new self($host, $name, $user, $pwd, $connect);
return $object;
}
/**
*
* @param $sql
* @Return [对象]
*/
private function Query($sql)
{
if(empty($sql)) return '';
try
{
$rs = $this->obj->query($sql);
if(!is_object($rs)) exit('DB Non Object Error');
$rs->setFetchMode(PDO::FETCH_ASSOC);
return $rs;
}
catch(PDOException $e)
{
exit('DB Resources Error');
}
}
/**
*
* @param $sql
* @return [二维数组或空字符串]
*/
public function GetAll($sql)
{
$data = $this->Query($sql)->fetchAll();
return empty($data) ? '' : $data;
}
/**
*
* @param $sql
* @return [一维数组或空字符串]
*/
public function GetRow($sql)
{
$data = $this->Query($sql)->fetch();
return empty($data) ? '' : $data;
}
/**
*
* @param $sql
* @return [字符串或空字符串]
*/
public function GetOne($sql)
{
$data = $this->Query($sql)->fetchColumn();
return empty($data) ? '' : $data;
}
/**
*
* @param $sql
* @return [一维数组或空字符串]
*/
public function GetCol($sql)
{
if(empty($sql)) return '';
$data = array();
$rs = $this->obj->query($sql);
$rs->setFetchMode(PDO::FETCH_NUM);
while($row = $rs->fetch())
{
$data[] = $row;
}
return empty($data) ? '' : $data;
}
/**
*
* @param $sql
* @return [成功true, 失败false]
*/
public function Exec($sql)
{
if($this->obj->exec($sql)) return true;
return false;
}
/**
*
* @param $sql
* @return [成功返回自增id(表无自增id则0), 失败-1]
*/
public function Insert($sql)
{
if($this->obj->exec($sql)) return $this->obj->lastInsertId();
return -1;
}
/**
*
*/
public function StartTrans()
{
$this->obj->beginTransaction();
}
/**
*
*/
public function Commit()
{
$this->obj->commit();
}
/**
*
*/
public function RollBack()
{
$this->obj->rollBack();
}
}
?>
页:
[1]