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.13333515.buzz防采集請勿采集本網。

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 ([email protected] 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.13333515.buzz請勿采集。

免責聲明 - 關于我們 - 聯系我們 - 廣告聯系 - 友情鏈接 - 幫助中心 - 頻道導航
Copyright © 2017 www.13333515.buzz All Rights Reserved
3排列五开奖结果