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

124 lines
2.3 KiB
PHP
Raw Normal View History

<?php
class dbh
{
private $db; //传入PDO对象.
2013-04-19 10:03:57 +00:00
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{
$datas[] = "'".$v."'";
}
}
if($return == false){
$fields = join(",",$fields);
$datas = join(",",$datas);
$sql = "INSERT INTO \"".$table."\" ($fields) VALUES ($datas)";
2013-04-19 10:03:57 +00:00
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;
}
2013-04-19 10:03:57 +00:00
}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))
{
2013-04-19 10:03:57 +00:00
$ups[] = '"'.$k.'"='.$v;
}else{
$ups[] = '"'.$k.'"=\''.$v."'";
}
}
2013-04-19 10:03:57 +00:00
$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
}