table=is_null($table)?C('TABLE_NAME'):$table;try{//self::$links=newPdo("mysql:host=127,0,0.1;dbname=c61",'root','welcome');self::$links=newPdo('mysql:host='.C('DB_HOST').';dbname='.C('DB_NAME'),C('DB_USER'),C('DB_PWD'));//设置字符编码self::$links->query('SETNAMESUTF8');//设置错误抛出类型self::$links->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);$this->_opt();}catch(PDOException$e){$e->getMessage();}}//定义opt属性privatefunction_opt(){$this->opt=array('field'=>"",'where'=>'','group'=>'','having'=>'','order'=>'','limit'=>'',);}//定义myquery方法publicfunctionmyquery($sql=null){//执行query方法,返回结果集对象$result=self::$links->query("$sql");//取出结果集赋值给数组$rows=$result->fetchAll(PDO::FETCH_ASSOC);return$rows;}//定义all方法publicfunctionall(){//组合字符串$sql="select".$this->opt['field']."from".$this->table.$this->opt['where'].$this->opt['group'].$this->opt['having'].$this->opt['order'].$this->opt['limit'];echo$sql;return$this->myquery($sql);}//定义field方法publicfunctionfield($sql=''){//需要判断''的情况//给feild元素赋值$this->opt['field']=$sql;return$this;}publicfunctionwhere($sql=''){$this->opt['where']="where".$sql;return$this;}publicfunctionorder($sql=''){$this->opt['order']="orderby".$sql;return$this;}publicfunctionlimit($sql=''){$this->opt['limit']="limit".$sql;return$this;}//定义find()执行publicfunctionfind(){$data=$this->limit(1)->all();//current()返回数组中当前的元素$data=current($data);return$data;}//别名函数onepublicfunctionone(){return$this->find();}//没有结果集的方法publicfunctionmyexec($sql){//echo$sql;$rows=self::$links->exec($sql);if($rows){echo"成功执行{$rows}条数据";return$rows;}else{halt('执行失败');return;}}publicfunctiondelete(){//必须判断where存不存在if(!empty($this->opt['where'])){$sql="deletefrom".$this->table.$this->opt['where'];return$this->myexec($sql);}else{halt('删除必须有where语句');return;}}//定义自动转义方法privatefunction_safe_str($str){//判断是否用户提交的数据,包括post,get,cookie.//如果值为1时为开启,则系统自动转义,如果不为1时,需要调用stripslashes函数转义.if(!get_magic_quotes_gpc()){$str=addslashes($str);};return$str;}//创建添加方法publicfunctionadd($data=null){//如果没有传递参数,使用$_post的值//否则使用传递的值.if(is_null($data))$data=$_POST;//定义存储字段和值的变量$field='';$values='';foreach($dataas$f=>$v){$field.="".$this->_safe_str($f).",";$values.="'".$this->_safe_str($v)."',";}//去除末尾的,号$field=rtrim($field,',');$values=rtrim($values,',');//insertintomessage(title,cid)values('易建联回到中国',2);//组合$sql语句,使用myexec执行.$sql="insertinto".$this->table.'('.$field.')values('.$values.')';echo$sql;return$this->myexec($sql);}//修改方法publicfunctionupdate($data=null){if(empty($_POST))return;if(is_null($data))$data=$_POST;//echo$sql;//如果没设置where语句if(!empty($this->opt['where'])){//updatearcsettitle='快学网',cid='2'whereaid=14;$values='';foreach($dataas$f=>$v){//组合$sql语句$values.=''.$this->_safe_str($f)."='".$this->_safe_str($v)."',";}//echo$values;$values=rtrim($values,",");echo$values;$sql="update".$this->table."set".$values.$this->opt['where'];return$this->myexec($sql);}else{halt('更新语句必须有where语句');return;}}}}?>