[php]代码库
class PdoHelper {
private $dsn;
private $usn;
private $pwd;
private $options;
function __construct($dsn, $usn, $pwd, $options = array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8')) {
$this->dsn = $dsn;
$this->usn = $usn;
$this->pwd = $pwd;
$this->options = $options;
}
public function GetPDOStatement() {
return new PDO($this->dsn, $this->usn, $this->pwd, $this->options);
}
//获得数据集
public function GetData($sql, $parames = array()) {
$dbh = $this->GetPDOStatement();
if (count($parames) > 0) {
$stmt = $dbh->prepare($sql);
$keys = array_keys($parames);
foreach ($keys as $key) {
$stmt->bindValue($key, $parames[$key]);
}
$stmt->execute();
return $stmt->fetchAll();
} else {
$query = $dbh->query($sql);
if ($query) {
return $query->fetchAll();
}
}
return FALSE;
}
//获得数据行
public function GetRow($sql, $parames = array()) {
$dbh = $this->GetPDOStatement();
if (count($parames) > 0) {
$stmt = $dbh->prepare($sql);
$keys = array_keys($parames);
foreach ($keys as $key) {
$stmt->bindValue($key, $parames[$key]);
}
$stmt->execute();
return $stmt->fetch();
} else {
$query = $dbh->query($sql);
if ($query) {
return $query->fetch();
}
}
return FALSE;
}
//获得一个值
public function GetValue($sql, $parames = array()) {
$dbh = $this->GetPDOStatement();
if (count($parames) > 0) {
$stmt = $dbh->prepare($sql);
$keys = array_keys($parames);
foreach ($keys as $key) {
$stmt->bindValue($key, $parames[$key]);
}
$stmt->execute();
return $stmt->fetchColumn();
} else {
$query = $dbh->query($sql);
if ($query) {
return $query->fetchColumn();
}
}
return FALSE;
}
//执行一条查询
public function Execute($sql, $parames = array()) {
$dbh = $this->GetPDOStatement();
if (count($parames) > 0) {
$stmt = $dbh->prepare($sql);
$keys = array_keys($parames);
foreach ($keys as $key) {
$stmt->bindValue($key, $parames[$key]);
}
return $stmt->execute();
} else {
return $dbh->exec($sql);
}
}
//执行插入 并且返回最后插入的ID
public function InsertDataGetLastID($sql, $parames = array()) {
$dbh = $this->GetPDOStatement();
if (count($parames) > 0) {
$stmt = $dbh->prepare($sql);
$keys = array_keys($parames);
foreach ($keys as $key) {
$stmt->bindValue($key, $parames[$key]);
}
$stmt->execute();
return $dbh->lastInsertId();
} else {
$dbh->exec($sql);
return $dbh->lastInsertId();
}
}
}