一直在使用框架,如今脱离了框架居然发现自己不会写程序了,这两天一直在做一个程序安全方面的应用,程序很老旧,代码质量很糟糕,我决定重新去构建这套系统,但是使用自己得框架
第一篇PDO数据库底层操作篇
private $db;
private $trans_ing = false;
private $db_err;
public function __construct()
{
$dsn = 'mysql:host=' . DB_HOST . ';dbname=' . DB_NAME . ';port=' . DB_PORT;
for ($i = 0; $i < 3; $i++) {
try {
$this->db = new PDO($dsn, DB_USER, DB_PASS, array(
PDO::ATTR_PERSISTENT => false,
PDO::ATTR_CASE => PDO::CASE_NATURAL,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_AUTOCOMMIT => true,
PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => true,
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',
));
break;
} catch (Exception $e) {
if ($i >= 2) throw new Exception('连接数据库失败,请重试');
}
}
}
public function getError()
{
return $this->db_err;
}
//插入
public function insert($table, $data)
{
$fields = '';
$values = '';
$realValues = array();
foreach ($data as $k => $v) {
if ($v === null) {
continue;
}
$fields .= '`' . $k . '`,';
$values .= ":{$k},";
$realValues[":{$k}"] = strval($v);
}
$sql = 'INSERT INTO `' . $table . '` (' . substr($fields, 0, -1) . ') VALUES (' . substr($values, 0, -1) . ')';
$pre = $this->db->prepare($sql);
if (!$pre) {
return false;
}
$result = $pre->execute($realValues);
if ($result) {
return $this->db->lastInsertId();
}
return false;
}
//更新
public function update($table, $data, $where = array())
{
$fields = '';
$realValues = array();
foreach ($data as $k => $v) {
if ($v === null) {
continue;
}
$fields .= ",`{$k}`=:{$k}";
$realValues[":{$k}"] = strval($v);
}
$fields = substr($fields, 1, strlen($fields) - 1);
$whereSql = '';
$whereValues = array();
foreach ($where as $k => $v) {
$whereSql .= " AND `{$k}`=:{$k}_1";
$whereValues[":{$k}_1"] = strval($v);
}
$realValues = array_merge($whereValues, $realValues);
$sql = "UPDATE `{$table}` SET {$fields} WHERE 1 {$whereSql}";
$pre = $this->db->prepare($sql);
if (!$pre) {
return false;
}
try {
$ret = $pre->execute($realValues);
return $ret;
} catch (Exception $e) {
$this->db_err = $e->getMessage();
return false;
}
}
网友评论