php mysql 封装类实例代码

来源:本网整理

php封装好的mysql操作库类文件mysql.class.php:phpclass Mysql{数据库连接返回值private$conn;[构造函数,返回值给$conn]param[string]$hostname[主机名]param[string]$username[用户名]param[string]$password[密码]param[string]$dbname[数据库名]param[string]$charset[字符集]return[null]function_construct($hostname,$username,$password,$dbname,$charset='utf8'){config=mysql_connect($hostname,$username,$password);if!config){echo '连接失败,请联系管理员';exit;}this->conn=$config;res=mysql_select_db($dbname);if!res){echo '连接失败,请联系管理员';exit;}mysql_set_charset($charset);}function_destruct(){mysql_close();}[getAll 获取所有信息]param[string]$sql[sql语句]return[array][返回二维数组]function getAll($sql){result=mysql_query($sql,$this->conn);data=array();if($result&mysql_num_rows($result)>0){while($row=mysql_fetch_assoc($result)){data[]=$row;}}return$data;}[getOne 获取单条数据]param[string]$sql[sql语句]return[array][返回一维数组]function getOne($sql){result=mysql_query($sql,$this->conn);data=array();if($result&mysql_num_rows($result)>0){data=mysql_fetch_assoc($result);}return$data;}[getOne 获取单条数据]param[string]$table[表名]param[string]$data[由字段名当键,属性当键值的一维数组]return[type][返回false或者插入数据的id]function insert($table,$data){str='';str.="INSERT INTO `$table`;str.="(`".implode("`,`",array_keys($data))."`);str.="VALUES;str.="('".implode("','",$data)."');res=mysql_query($str,$this->conn);if($res&mysql_affected_rows()>0){return mysql_insert_id();}else{return false;}}[update 更新数据库]param[string]$table[表名]param[array]$data[更新的数据,由字段名当键,属性当键值的一维数组]param[string]$where[条件,‘字段名’=‘字段属性’]return[type][更新成功返回影响的行数,更新失败返回false]function update($table,$data,$where){sql='UPDATE '.$table.' SET ';foreach($data as$key=>$value){sql.="`{$key}`='{$value}',;}sql=rtrim($sql,',');sql.="WHERE$where;res=mysql_query($sql,$this->conn);if($res&mysql_affected_rows()){return mysql_affected_rows();}else{return false;}}[delete 删除数据]param[string]$table[表名]param[string]$where[条件,‘字段名’=‘字段属性’]return[type][成功返回影响的行数,失败返回false]function del($table,$where){sql="DELETE FROM `{$table}` WHERE {$where};res=mysql_query($sql,$this->conn);if($res&mysql_affected_rows()){return mysql_affected_rows();}else{return false;}}}使用案例:php包含数据库操作类文件include 'mysql.class.php';设置传入参数hostname='localhost';username='root';password='123456';dbname='aisi';charset='utf8';实例化对象db=new Mysql($hostname,$username,$password,$dbname);获取一条数据sql="SELECT count(as_article_id)as count FROM as_article where as_article_type_id=1;count=$db->getOne($sql);获取多条数据sql="SELECT*FROM as_article where as_article_type_id=1 order by as_article_addtime desc limit$start,$limit;service=$db->getAll($sql);插入数据arr=array'as_article_title'=>'数据库操作类','as_article_author'=>'rex',res=$db->insert('as_article',$arr);更新数据arr=array'as_article_title'=>'实例化对象','as_article_author'=>'Lee',where="as_article_id=1;res=$db->update('as_article',$arr,$where);删除数据where="as_article_id=1;res=$db->del('as_article',$where);www.zgxue.com防采集请勿采集本网。

s">

php mysql 封装类实例代码

作者:damys 字体:[增加 减小] 类型:转载 时间:2016-09-18 我要评论 这篇文章主要介绍了php mysql 封装类实例代码,非常不错,具有参考借鉴价值,需要的朋友可以参考下 ">

废话不多说了,具体代码如下所示:

get_navigation(){.} 内,query之前 加一句 global$db;或者改为 function get_navigation($db){.} navigation=get_navigation($db);

<?phpclass mysql {private $db_host; //数据库主机private $db_user; //数据库用户名private $db_pwd; //数据库用户名密码private $db_database; //数据库名private $conn; //数据库连接标识;private $result; //执行query命令的结果资源标识private $sql; //sql执行语句private $row; //返回的条目数private $coding; //数据库编码,GBK,UTF8,gb2312private $bulletin = true; //是否开启错误记录private $show_error = false; //测试阶段,显示所有错误,具有安全隐患,默认关闭private $is_error = false; //发现错误是否立即终止,默认true,建议不启用,因为当有问题时用户什么也看不到是很苦恼的/*构造函数*/public function __construct($db_host, $db_user, $db_pwd, $db_database, $conn, $coding) {$this->db_host = $db_host;$this->db_user = $db_user;$this->db_pwd = $db_pwd;$this->db_database = $db_database;$this->conn = $conn;$this->coding = $coding;$this->connect();}/*数据库连接*/public function connect() {if ($this->conn == "pconn") {//永久链接$this->conn = mysql_pconnect($this->db_host, $this->db_user, $this->db_pwd);} else {//即使链接$this->conn = mysql_connect($this->db_host, $this->db_user, $this->db_pwd);}if (!mysql_select_db($this->db_database, $this->conn)) {if ($this->show_error) {$this->show_error("数据库不可用:", $this->db_database);}}mysql_query("SET NAMES $this->coding");}/*数据库执行语句,可执行查询添加修改删除等任何sql语句*/public function query($sql) {if ($sql == "") {$this->show_error("SQL语句错误:", "SQL查询语句为空");}$this->sql = $sql;$result = mysql_query($this->sql, $this->conn);if (!$result) {//调试中使用,sql语句出错时会自动打印出来if ($this->show_error) {$this->show_error("错误SQL语句:", $this->sql);}} else {$this->result = $result;}return $this->result;}/*创建添加新的数据库*/public function create_database($database_name) {$database = $database_name;$sqlDatabase = 'create database ' . $database;$this->query($sqlDatabase);}/*查询服务器所有数据库*///将系统数据库与用户数据库分开,更直观的显示?public function show_databases() {$this->query("show databases");echo "现有数据库:" . $amount = $this->db_num_rows($rs);echo "<br />";$i = 1;while ($row = $this->fetch_array($rs)) {echo "$i $row[Database]";echo "<br />";$i++;}}//以数组形式返回主机中所有数据库名public function databases() {$rsPtr = mysql_list_dbs($this->conn);$i = 0;$cnt = mysql_num_rows($rsPtr);while ($i < $cnt) {$rs[] = mysql_db_name($rsPtr, $i);$i++;}return $rs;}/*查询数据库下所有的表*/public function show_tables($database_name) {$this->query("show tables");echo "现有数据库:" . $amount = $this->db_num_rows($rs);echo "<br />";$i = 1;while ($row = $this->fetch_array($rs)) {$columnName = "Tables_in_" . $database_name;echo "$i $row[$columnName]";echo "<br />";$i++;}}/*mysql_fetch_row() array $row[0],$row[1],$row[2]mysql_fetch_array() array $row[0] 或 $row[id]mysql_fetch_assoc() array 用$row->content 字段大小写敏感mysql_fetch_object() object 用$row[id],$row[content] 字段大小写敏感*//*取得结果数据*/public function mysql_result_li() {return mysql_result($str);}/*取得记录集,获取数组-索引和关联,使用$row['content'] */public function fetch_array($resultt="") {if($resultt<>""){return mysql_fetch_array($resultt);}else{return mysql_fetch_array($this->result);}}//获取关联数组,使用$row['字段名']public function fetch_assoc() {return mysql_fetch_assoc($this->result);}//获取数字索引数组,使用$row[0],$row[1],$row[2]public function fetch_row() {return mysql_fetch_row($this->result);}//获取对象数组,使用$row->contentpublic function fetch_Object() {return mysql_fetch_object($this->result);}//简化查询selectpublic function findall($table) {$this->query("SELECT * FROM $table");}//简化查询selectpublic function select($table, $columnName = "*", $condition = '', $debug = '') {$condition = $condition ? ' Where ' . $condition : NULL;if ($debug) {echo "SELECT $columnName FROM $table $condition";} else {$this->query("SELECT $columnName FROM $table $condition");}}//简化删除delpublic function delete($table, $condition, $url = '') {if ($this->query("DELETE FROM $table WHERE $condition")) {if (!empty ($url))$this->Get_admin_msg($url, '删除成功!');}}//简化插入insertpublic function insert($table, $columnName, $value, $url = '') {if ($this->query("INSERT INTO $table ($columnName) VALUES ($value)")) {if (!empty ($url))$this->Get_admin_msg($url, '添加成功!');}}//简化修改updatepublic function update($table, $mod_content, $condition, $url = '') {//echo "UPDATE $table SET $mod_content WHERE $condition"; exit();if ($this->query("UPDATE $table SET $mod_content WHERE $condition")) {if (!empty ($url))$this->Get_admin_msg($url);}}/*取得上一步 INSERT 操作产生的 ID*/public function insert_id() {return mysql_insert_id();}//指向确定的一条数据记录public function db_data_seek($id) {if ($id > 0) {$id = $id -1;}if (!@ mysql_data_seek($this->result, $id)) {$this->show_error("SQL语句有误:", "指定的数据为空");}return $this->result;}// 根据select查询结果计算结果集条数public function db_num_rows() {if ($this->result == null) {if ($this->show_error) {$this->show_error("SQL语句错误", "暂时为空,没有任何内容!");}} else {return mysql_num_rows($this->result);}}// 根据insert,update,delete执行结果取得影响行数public function db_affected_rows() {return mysql_affected_rows();}//输出显示sql语句public function show_error($message = "", $sql = "") {if (!$sql) {echo "<font color='red'>" . $message . "</font>";echo "<br />";} else {echo "<fieldset>";echo "<legend>错误信息提示:</legend><br />";echo "<div style='font-size:14px; clear:both; font-family:Verdana, Arial, Helvetica, sans-serif;'>";echo "<div style='height:20px; background:#000000; border:1px #000000 solid'>";echo "<font color='white'>错误号:12142</font>";echo "</div><br />";echo "错误原因:" . mysql_error() . "<br /><br />";echo "<div style='height:20px; background:#FF0000; border:1px #FF0000 solid'>";echo "<font color='white'>" . $message . "</font>";echo "</div>";echo "<font color='red'><pre>" . $sql . "</pre></font>";$ip = $this->getip();if ($this->bulletin) {$time = date("Y-m-d H:i:s");$message = $message . "\r\n$this->sql" . "\r\n客户IP:$ip" . "\r\n时间 :$time" . "\r\n\r\n";$server_date = date("Y-m-d");$filename = $server_date . ".txt";$file_path = "error/" . $filename;$error_content = $message;//$error_content="错误的数据库,不可以链接";$file = "error"; //设置文件保存目录//建立文件夹if (!file_exists($file)) {if (!mkdir($file, 0777)) {//默认的 mode 是 0777,意味着最大可能的访问权die("upload files directory does not exist and creation failed");}}//建立txt日期文件if (!file_exists($file_path)) {//echo "建立日期文件";fopen($file_path, "w+");//首先要确定文件存在并且可写if (is_writable($file_path)) {//使用添加模式打开$filename,文件指针将会在文件的开头if (!$handle = fopen($file_path, 'a')) {echo "不能打开文件 $filename";exit;}//将$somecontent写入到我们打开的文件中。if (!fwrite($handle, $error_content)) {echo "不能写入到文件 $filename";exit;}//echo "文件 $filename 写入成功";echo "——错误记录被保存!";//关闭文件fclose($handle);} else {echo "文件 $filename 不可写";}} else {//首先要确定文件存在并且可写if (is_writable($file_path)) {//使用添加模式打开$filename,文件指针将会在文件的开头if (!$handle = fopen($file_path, 'a')) {echo "不能打开文件 $filename";exit;}//将$somecontent写入到我们打开的文件中。if (!fwrite($handle, $error_content)) {echo "不能写入到文件 $filename";exit;}//echo "文件 $filename 写入成功";echo "——错误记录被保存!";//关闭文件fclose($handle);} else {echo "文件 $filename 不可写";}}}echo "<br />";if ($this->is_error) {exit;}}echo "</div>";echo "</fieldset>";echo "<br />";}//释放结果集public function free() {@ mysql_free_result($this->result);}//数据库选择public function select_db($db_database) {return mysql_select_db($db_database);}//查询字段数量public function num_fields($table_name) {//return mysql_num_fields($this->result);$this->query("select * from $table_name");echo "<br />";echo "字段数:" . $total = mysql_num_fields($this->result);echo "<pre>";for ($i = 0; $i < $total; $i++) {print_r(mysql_fetch_field($this->result, $i));}echo "</pre>";echo "<br />";}//取得 MySQL 服务器信息public function mysql_server($num = '') {switch ($num) {case 1 :return mysql_get_server_info(); //MySQL 服务器信息break;case 2 :return mysql_get_host_info(); //取得 MySQL 主机信息break;case 3 :return mysql_get_client_info(); //取得 MySQL 客户端信息break;case 4 :return mysql_get_proto_info(); //取得 MySQL 协议信息break;default :return mysql_get_client_info(); //默认取得mysql版本信息}}//析构函数,自动关闭数据库,垃圾回收机制public function __destruct() {if (!empty ($this->result)) {$this->free();}mysql_close($this->conn);} //function __destruct();/*获得客户端真实的IP地址*/function getip() {if (getenv("HTTP_CLIENT_IP") && strcasecmp(getenv("HTTP_CLIENT_IP"), "unknown")) {$ip = getenv("HTTP_CLIENT_IP");} elseif (getenv("HTTP_X_FORWARDED_FOR") && strcasecmp(getenv("HTTP_X_FORWARDED_FOR"), "unknown")) {$ip = getenv("HTTP_X_FORWARDED_FOR");} elseif (getenv("REMOTE_ADDR") && strcasecmp(getenv("REMOTE_ADDR"), "unknown")) {$ip = getenv("REMOTE_ADDR");} elseif (isset ($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], "unknown")) {$ip = $_SERVER['REMOTE_ADDR'];} else {$ip = "unknown";}return ($ip);}function inject_check($sql_str) { //防止注入$check = eregi('select|insert|update|delete|\'|\/\*|\*|\.\.\/|\.\/|union|into|load_file|outfile', $sql_str);if ($check) {echo "输入非法注入内容!";exit ();} else {return $sql_str;}}function checkurl() { //检查来路if (preg_replace("/https?:\/\/([^\:\/]+).*/i", "\\1", $_SERVER['HTTP_REFERER']) !== preg_replace("/([^\:]+).*/", "\\1", $_SERVER['HTTP_HOST'])) {header("Location: http://www.dareng.com");exit();}}}?>

下面这个,是针对php5的一个简单数据库封装类,适合学习,其他的如删除、更新等操作,你可以自己加上: php class Mysql{/首先定义一个类,首写字母大写 public$host;服务器名,访问修饰符PUBLIC证明$host

以上所述是小编给大家介绍的php mysql 封装类实例代码,希望对大家有所帮助,如果大家有任何疑问欢迎给我留言,小编会及时回复大家的,在此也非常感谢大家对突袭网网站的支持!

?php class Mysql{ private$db_host;private$db_user;private$db_pass;private$db_table;private$ut;function_construct($db_host,$db_user,$db_pass,$db_table,$ut){ this->db_host=$db_host;

?phpclass MMysql {protected static$_dbh=null;静态属性,所有数据库实例共用,避免重复连接数据库protected$_dbType='mysql';protected$_pconnect=true;是否使用长连接protected$_host='localhost';protected$_port=3306;protected$_user='root';protected$_pass='root';protected$_dbName=null;数据库名protected$_sql=false;最后一条sql语句protected$_where='';protected$_order='';protected$_limit='';protected$_field='*';protected$_clear=0;状态,0表示查询条件干净,1表示查询条件污染protected$_trans=0;事务指令数初始化类e799bee5baa6e997aee7ad94e58685e5aeb931333363373763param array$conf 数据库配置public function_construct(array$conf){class_exists('PDO')or die("PDO:class not exists.");this->_host=$conf['host'];this->_port=$conf['port'];this->_user=$conf['user'];this->_pass=$conf['passwd'];this->_dbName=$conf['dbname'];连接数据库if(is_null(self:$_dbh)){this->_connect();}}连接数据库的方法protected function_connect(){dsn=$this->_dbType.':host='.$this->_host.';port='.$this->_port.';dbname='.$this->_dbName;options=$this->_pconnect?array(PDO:ATTR_PERSISTENT=>true):array();try {dbh=new PDO($dsn,$this->_user,$this->_pass,$options);dbh->setAttribute(PDO:ATTR_ERRMODE,PDO:ERRMODE_EXCEPTION);设置如果sql语句执行错误则抛出异常,事务会自动回滚dbh->setAttribute(PDO:ATTR_EMULATE_PREPARES,false);禁用prepared statements的仿真效果(防SQL注入)} catch(PDOException$e){die('Connection failed:'.$e->getMessage());}dbh->exec('SET NAMES utf8');self:$_dbh=$dbh;}字段和表名添加 `符号保证指令中使用关键字不出错 针对mysqlparam string$valuereturn stringprotected function_addChar($value){if('*'=$value|false!strpos($value,'(')|false!strpos($value,'.')|false!strpos($value,'`')){如果包含*或者 使用了sql方法 则不作处理} elseif(false=strpos($value,'`')){value='`'.trim($value).'`';}return$value;}取得数据表的字段信息param string$tbName 表名return arrayprotected function_tbFields($tbName){sql='SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME="'.$tbName.'"AND TABLE_SCHEMA="'.$this->_dbName.'"';stmt=self:$_dbh->prepare($sql);stmt->execute();result=$stmt->fetchAll(PDO:FETCH_ASSOC);ret=array();foreach($result as$key=>$value){ret[$value['COLUMN_NAME']]=1;}return$ret;}过滤并格式化数据表字段param string$tbName 数据表名param array$data POST提交数据return array$newdataprotected function_dataFormat($tbName,$data){if!is_array($data))return array();table_column=$this->_tbFields($tbName);ret=array();foreach($data as$key=>$val){if!is_scalar($val))continue;值不是标量则跳过if(array_key_exists($key,$table_column)){key=$this->_addChar($key);if(is_int($val)){val=intval($val);} elseif(is_float($val)){val=floatval($val);} elseif(preg_match('/^\\(\\w*(\\+|\\-|\\*|\\/)?\\w*\\)$/i',$val)){支持在字段的值里面直接使用其它字段,例如(score+1)(name)必须包含括号val=$val;} elseif(is_string($val)){val='"'.addslashes($val).'"';}ret[$key]=$val;}}return$ret;}执行查询 主要针对 SELECT,SHOW 等指令param string$sql sql指令return mixedprotected function_doQuery($sql=''){this->_sql=$sql;pdostmt=self:$_dbh->prepare($this->_sql);prepare或者query 返回一个PDOStatementpdostmt->execute();result=$pdostmt->fetchAll(PDO:FETCH_ASSOC);return$result;}执行语句 针对 INSERT,UPDATE 以及DELETE,exec结果返回受影响的行数param string$sql sql指令return integerprotected function_doExec($sql=''){this->_sql=$sql;return self:$_dbh->exec($this->_sql);}执行sql语句,自动判断进行查询或者执行操作param string$sql SQL指令return mixedpublic function doSql($sql=''){queryIps='INSERT|UPDATE|DELETE|REPLACE|CREATE|DROP|LOAD DATA|SELECT.*INTO|COPY|ALTER|GRANT|REVOKE|LOCK|UNLOCK';if(preg_match('/^\\s*?('.$queryIps.')\\s+i',$sql)){return$this->_doExec($sql);}else {查询操作return$this->_doQuery($sql);}}获取最近一次查询的sql语句return String 执行的SQLpublic function getLastSql(){return$this->_sql;}插入方法param string$tbName 操作的数据表名param array$data 字段-值的一维数组return int 受影响的行数public function insert($tbName,array$data){data=$this->_dataFormat($tbName,$data);if!data)return;sql="insert into".$tbName."(".implode(',',array_keys($data)).")values(".implode(',',array_values($data)).");return$this->_doExec($sql);}删除方法param string$tbName 操作的数据表名return int 受影响的行数public function delete($tbName){安全考虑,阻止全表删除if!trim($this->_where))return false;sql="delete from".$tbName."".$this->_where;this->_clear=1;this->_clear();return$this->_doExec($sql);}更新函数param string$tbName 操作的数据表名param array$data 参数数组return int 受影响的行数public function update($tbName,array$data){安全考虑,阻止全表更新if!trim($this->_where))return false;data=$this->_dataFormat($tbName,$data);if!data)return;valArr='';foreach($data as$k=>$v){valArr[]=$k.'='.$v;}valStr=implode(',',$valArr);sql="update".trim($tbName)."set".trim($valStr)."".trim($this->_where);return$this->_doExec($sql);}查询函数param string$tbName 操作的数据表名return array 结果集public function select($tbName=''){sql="select".trim($this->_field)."from".$tbName."".trim($this->_where)."".trim($this->_order)."".trim($this->_limit);this->_clear=1;this->_clear();return$this->_doQuery(trim($sql));}param mixed$option 组合条件的二维数组,例:$option['field1']=array(1,'=>','or')return$thispublic function where($option){if($this->_clear>0)$this->_clear();this->_where=' where ';logic='and';if(is_string($option)){this->_where.=$option;}elseif(is_array($option)){foreach($option as$k=>$v){if(is_array($v)){relative=isset($v[1])?v[1]:'=';logic=isset($v[2])?v[2]:'and';condition='('.$this->_addChar($k).' '.$relative.' '.$v[0].')';}else {logic='and';condition='('.$this->_addChar($k).'='.$v.')';}this->_where.=isset($mark)?logic.$condition:$condition;mark=1;}}return$this;}设置排序param mixed$option 排序条件数组 例:array('sort'=>'desc')return$thispublic function order($option){if($this->_clear>0)$this->_clear();this->_order=' order by ';if(is_string($option)){this->_order.=$option;}elseif(is_array($option)){foreach($option as$k=>$v){order=$this->_addChar($k).' '.$v;this->_order.=isset($mark)?','.$order:$order;mark=1;}}return$this;}设置查询行数及页数param int$page pageSize不为空时为页数,否则为行数param int$pageSize 为空则函数设定取出行数,不为空则设定取出行数及页数return$thispublic function limit($page,$pageSize=null){if($this->_clear>0)$this->_clear();if($pageSize=null){this->_limit="limit".$page;}else {pageval=intval(($page-1)*pageSize);this->_limit="limit".$pageval内容来自www.zgxue.com请勿采集。

免责声明 - 关于我们 - 联系我们 - 广告联系 - 友情链接 - 帮助中心 - 频道导航
Copyright © 2017 www.zgxue.com All Rights Reserved