一直在使用框架登钥,如今脫離了框架居然發(fā)現(xiàn)自己不會(huì)寫程序了纺腊,這兩天一直在做一個(gè)程序安全方面的應(yīng)用畔咧,程序很老舊,代碼質(zhì)量很糟糕揖膜,我決定重新去構(gòu)建這套系統(tǒng)盒卸,但是使用自己得框架
第一篇PDO數(shù)據(jù)庫(kù)底層操作篇
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('連接數(shù)據(jù)庫(kù)失敗,請(qǐng)重試');
}
}
}
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;
}
}