westdc-zf1/application/models/helper/dbh.php

137 lines
2.6 KiB
PHP

<?php
class dbh
{
private $db; //传入PDO对象.
private $product = 0; //产品环境
function __construct($db)
{
$this->db = $db;
}
function insert($table,$data,$return=false)
{
$fields = array();
$datas = array();
foreach($data as $k=>$v)
{
$fields[] = '"'.$k.'"';
if(is_int($v) || is_float($v) || is_bool($v))
{
$datas[] = $v;
}else{
if(preg_match("/\'/",$v))
{
$v = preg_replace("/\'/","''",$v);
}
$datas[] = "'".$v."'";
}
}
$fields = join(",",$fields);
$datas = join(",",$datas);
if($return == false){
$sql = "INSERT INTO \"".$table."\" ($fields) VALUES ($datas)";
try{
return $this->db->exec($sql);
}catch (Exception $e) {
if($this->product)
{
return false;
}else{
echo 'Caught exception: '. $e->getMessage(). "\n";
}
}
}else{
$sql = "INSERT INTO \"".$table."\" ($fields) VALUES ($datas) RETURNING id";
try{
$sth = $this->db->prepare($sql);
if($sth->execute())
{
$temp = $sth->fetch(PDO::FETCH_ASSOC);
return $temp['id'];
}else{
return false;
}
}catch (Exception $e) {
if($this->product)
{
return false;
}else{
echo 'Caught exception: '. $e->getMessage(). "\n";
}
}
}
}//insert
function update($table,$data,$condition="",$return=false)
{
$ups = array();
foreach($data as $k=>$v)
{
if(is_int($v) || is_float($v) || is_bool($v))
{
$ups[] = '"'.$k.'"='.$v;
}else{
if(preg_match("/\'/",$v))
{
$v = preg_replace("/\'/","''",$v);
}
if(preg_match("/\"/",$v))
{
$v = preg_replace("/\"/","''",$v);
}
$ups[] = '"'.$k.'"=\''.$v."'";
}
}
$fields = join(",",$ups);
if(!empty($condition))
{
$wheresql = " WHERE ".$condition;
}else{
$wheresql = "";
}
if($return == false){
try{
$sql = "UPDATE \"".$table."\" SET $fields $wheresql";
if($this->db->exec($sql))
{
return true;
}else{
return false;
}
}catch (Exception $e) {
if($this->product)
{
return false;
}else{
echo 'Caught exception: '. $e->getMessage(). "\n";
}
}
}else{
try{
$sql = "UPDATE \"".$table."\" SET $fields $wheresql";
return $this->db->exec($sql);
}catch (Exception $e) {
if($this->product)
{
return false;
}else{
echo "<pre>";
echo $sql."\r\n";
echo 'Caught exception: '. $e->getMessage(). "\r\n";
echo "</pre>";
}
}
}
}//update
}