Home  >  Article  >  Backend Development  >  mysql operation class_PHP tutorial

mysql operation class_PHP tutorial

WBOY
WBOYOriginal
2016-07-13 17:49:16816browse

/**
* Database operation class
* 2011/8/25
* kcj
**/
class MyDB {
Private $db_host; //Database host name
Private $db_user; //Database user name
Private $db_pwd; //Database password
Private $db_database; //Database name
private $conn; //Connection ID
Private $result; //Result resource identifier of executing query command
private $row; //Number of entries returned
private $sql; //sql execution statement
Private $coding; //Database encoding
Private $bulletin=true; // Whether to enable error logging
Private $show_error=false; //During the testing phase, all errors are displayed, which has security risks and is closed by default
Private $is_error=false; //Whether to terminate immediately when an error is detected, the default is true, it is recommended not to enable it, because it is very distressing for users to not see anything when there is a problem
//Constructor
Function __construct($db_host,$db_user,$db_pwd,$db_database,$conn,$doding){
               $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();
                                   
}  
//Database connection
Public function connect(){
If($this->conn=="pconn"){
                     // Permanent connection
                 $this->conn=mysql_pconnect($this->db_host,$this->db_user,$this->db_pwd);
         }else{
                                                                                                                                                                          use   using                                                                    $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-& gt; show_error ("Database is unavailable:", $ this-& gt; db_database);
                                                                                                                                               } 
}  
         
//Database execution statement, any sql statement such as executable query, addition, modification, deletion etc.
Public function query($sql){
          if($sql==""){
                 $this->show_error("SQL statement error:", "SQL statement is empty");
         } 
          $this->sql=$sql;
           $result=mysql_query($this->sql,$this->conn);
If(!$result){
If($this->show_error){
                             $this->show_error("Error sql statement: ",$this->sql);
                                                                                                                                                                                                                   $this->result;
         } 
                                                              return   $result; }  
//Create and add a new database
Public function create_database($database_name){
           $database=$database_name;
            $sqlDatabase='create database'.$database;
             $this->query($sqlDatabase);
}  
//Query all databases on the server
//Separate the system database from the user for a more intuitive display
Public function show_database(){
          $this->query("show databases");
echo "The current database:".$amount=$this->db_num_rows($rs);
echo "
";
         $i=1;
While ($row=$this->fetch_array($rs)){
                echo "$i $row[Database]";
echo "
";
               $i++;
         } 
}  
//Return all database names in the host in the form of an array
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;
}  
//Query all tables under the database
Public function show_tables($database_name){
          $this->query("show tables");
echo "Existing database:".$amount=$this->db_num_rows($rs);
echo "
";
         $i=1;
While ($row=$this->fetch_array($rs)){
                $columnName="Tables_in_".$database_name;
                echo "$i $row[$columnName]";
echo "
";
               $i++;
         } 
}  
// Get the result set
Public function fetch_array($resultt=""){
If($resultt!=""){
                 return mysql_fetch_array($resultt);
                                                                                          return mysql_fetch_array($this->result);
         } 
}  
//Get the number of results $row['content']
Public function mysql_result_li(){
          return mysql_result($str);
}  
//Get the associative array $row['field name']
Public function fetch_assoc(){
           return mysql_fetch_assoc($this->result);
}  
//Get the numeric index array $row[0] $row[1] $row[2]
Public function fetch_row(){
          return mysql_fetch_row($this->result);
}  
//Get the object array, use $row->content
Public function fetch_Object(){
          return mysql_fetch_object($this->result);
}  
//Simplified query select
Public function findall($table){
          $this->query("select* from $table");
}  
//Simplified query select
Public 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");
         } 
}  
         
//Simplify deletion del
Public function delete($table,$condition,$url=''){
If($this->query("delete from $table where $condition")){
If(!emptyempty($url)){
                     $this->Get_admin_msg($url,'Delete successfully');
                                                                                                                                               } 
}  
//Simplified insertion
Public function insert($table,$columnName,$value,$url=''){
If($this->query("insert into $table ($columnName) values ​​($value)")){
If(!emptyempty($url)){
$this->Get_admin_msg($url,'Added successfully');
                                                                                                                                                                                                                                                                                                }  
//Simplified update update
Public function update($table,$mod_content,$condition,$url=''){
If($this->query("update $table set $mod_content where $condition")){
If(!emptyempty($url)){
$this->Get_admin_msg($url);
                                                                                                                                               } 
}  
//Get the id of the previous insert operation
     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 "" . $message . ""; 
            echo "
"; 
        }else{ 
             echo "

"; 
            echo "错误信息提示:
"; 
            echo "
"; 
           echo "
"; 
            echo "错误号:12142"; 
            echo "

"; 
            echo "错误原因:" . mysql_error() . "

"; 
           echo "
"; 
            echo "" . $message . ""; 
            echo "
";
echo "
" . $sql . "
";
$ip = $this->getip();
If ($this->bulletin) {
                  $time = date("Y-m-d H:i:s");
"rn$this->sql" . "rnCustomer IP:$ip" . "rnTime:$time" . "rnrn";

                    $server_date = date("Y-m-d");
                      $filename = $server_date . ".txt";
$file_path = "error/" . $filename;
                    $error_content = $message;
//$error_content="Wrong database, cannot be linked";
                   $file = "error"; //Set the file saving directory
//Create folder
if(!file_exists($file)){
If(!mkdir($file,0777)){
           die("upload files directory does not exist and creation failed");
}  
}
//Create txt date file
If(!file_exists($file_path)){
         fopen($file_path,"w+");
If(is_writable($file_path)){
If(!$handle=fopen($file_path,'a')){
echo "Cannot open file $filename";
exit;
                                                                                                                                      If(!fwrite($handle,$error_content)){
echo "Cannot write to file $filename";
exit;
                                                                                                                                      echo "——Error record is saved!";
             fclose($handle);

                                                                          echo "The file $filename is not writable";
         } 
}else {
If(is_writable($file_path)){
If(!$handle=fopen($file_path,'a')){
echo "Cannot open file $filename";
exit;
                                                                                                                                      If(!fwrite($handle,$error_content)){
echo "Cannot write to file $filename";
exit;
                                                                                                                                                  echo "——错误记录被保存!"; 
              fclose($handle); 
        }else { 
            echo "文件 $filename 不可写"; 
        } 
    } 
        } 
     echo "
";    
     if ($this->is_error) { 
          exit; 
            } 
        } 
     echo "
";
echo "
";
echo "
";
}  
//Release the result set
public function free(){
@mysql_free_result($this->result);
}  
//Database selection
Public function select_db($db_database){
Return mysql_select_db($db_database);
}  
//Query number of fields
Public function num_fields($table_name){
$this->query("select * from $table_name");
echo "
";
echo "Number of fields:".$total=mysql_num_fields($this->result);
for ($i=0;$i<$total;$i++){
            print_r(mysql_fetch_field($this->result,$i));
}  
echo "";
echo "
";
}  
//Get mysql server information
Public function mysql_server($num=''){
switch ($num){
case 1:
               return mysql_get_server_info();
break;
case 2:
               return mysql_get_host_info();
break;
case 3:
               return mysql_get_client_info();
break;
case 4:
               return mysql_get_proto_info();
break;
                   default:
                     return mysql_get_client_info();
}  
}  
public function __destruct(){
If(!emptyempty($this->result)){
$this->free();
}  
Mysql_close($this->conn);
}
//Get the real ID address of the client
function getip() {
If (getenv("HTTP_CLIENT_IP") && strcasecmp(getenv("HTTP_CLIENT_IP"), "unknown")) {
               $ip = getenv("HTTP_CLIENT_IP");
         } else
If (getenv("HTTP_X_FORWARDED_FOR") &&strcasecmp(getenv("HTTP_X_FORWARDED_FOR"), "unknown")) {
                   $ip = getenv("HTTP_X_FORWARDED_FOR");
              } else
If (getenv("REMOTE_ADDR") && strcasecmp(getenv("REMOTE_ADDR"), "unknown")) {
$ip = getenv("REMOTE_ADDR");
                                                                                                       If (isset ($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] &&strcasecmp($_SERVER['REMOTE_ADDR'], "unknown")) {
$ip = $_SERVER['REMOTE_ADDR'];
                                                                                                                                                           $ip = "unknown";
                                                                                                                                                                                  return ($ip);
}  
 
}


?>
/**
* Database operation class
* 2011/8/25
* kcj
**/
class MyDB {
private $db_host; //Database host name
private $db_user; //Database user name
private $db_pwd; //Database password
private $db_database; //Database name
private $conn; //Connection ID
private $result; //Result resource identifier of executing query command
private $row; //Number of entries returned
private $sql; //sql execution statement
private $coding; //Database encoding
private $bulletin=true; // Whether to enable error logging
private $show_error=false; //During the testing phase, all errors are displayed, which has security risks and is closed by default
private $is_error=false; //Whether to terminate immediately when an error is detected, the default is true, it is recommended not to enable it, because it is very distressing for users to not see anything when there is a problem
//Constructor
function __construct($db_host,$db_user,$db_pwd,$db_database,$conn,$doding){
          $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();

}
//Database connection
public function connect(){
if($this->conn=="pconn"){
//Permanent connection
$this->conn=mysql_pconnect($this->db_host,$this->db_user,$this->db_pwd);
}else{
//Even if connected
$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("Database unavailable:",$this->db_database);
}
}
}

//Database execution statement, any sql statement such as query addition, modification, deletion, etc. can be executed
public function query($sql){
if($sql==""){
$this->show_error("SQL statement error:","SQL statement is empty");
}
$this->sql=$sql;
$result=mysql_query($this->sql,$this->conn);
if(!$result){
If($this->show_error){
$this->show_error("Error sql statement:",$this->sql);
}
}else {
$this->result;
}
return $result;
}
//Create and add a new database
public function create_database($database_name){
        $database=$database_name;
$sqlDatabase='create database'.$database;
         $this->query($sqlDatabase);
}
//Query all databases on the server
//Separate the system database from the user for a more intuitive display
public function show_database(){
$this->query("show databases");
echo "The current database:".$amount=$this->db_num_rows($rs);
echo "
";
$i=1;
while ($row=$this->fetch_array($rs)){
echo "$i $row[Database]";
echo "
";
$i++;
}
}
//Return all database names in the host in the form of an array
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;
}
//Query all tables under the database
public function show_tables($database_name){
$this->query("show tables");
echo "Existing database:".$amount=$this->db_num_rows($rs);
echo "
";
$i=1;
while ($row=$this->fetch_array($rs)){
$columnName="Tables_in_".$database_name;
echo "$i $row[$columnName]";
echo "
";
$i++;
}
}
// Get the result set
public function fetch_array($resultt=""){
if($resultt!=""){
Return mysql_fetch_array($resultt);
}else {
Return mysql_fetch_array($this->result);
}
}
//Get the number of results $row['content']
public function mysql_result_li(){
Return mysql_result($str);
}
//Get associative array $row['field name']
public function fetch_assoc(){
Return mysql_fetch_assoc($this->result);
}
//Get the numeric index array $row[0] $row[1] $row[2]
public function fetch_row(){
Return mysql_fetch_row($this->result);
}
//Get the object array, use $row->content
public function fetch_Object(){
Return mysql_fetch_object($this->result);
}
//Simplified query select
public function findall($table){
$this->query("select* from $table");
}
//Simplified query select
public 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");
}
}

//Simplify deletion del
public function delete($table,$condition,$url=''){
if($this->query("delete from $table where $condition")){
If(!empty($url)){
$this->Get_admin_msg($url,'Delete successfully');
}
}
}
//Simplify insert
public function insert($table,$columnName,$value,$url=''){
If($this->query("insert into $table ($columnName) values ​​($value)")){
If(!empty($url)){
$this->Get_admin_msg($url,'Added successfully');
}
}

}
//Simplified update update
public function update($table,$mod_content,$condition,$url=''){
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 "" . $message . "";
            echo "
";
   }else{
     echo "
";
            echo "错误信息提示:
";
            echo "
";
           echo "
";
            echo "错误号:12142";
            echo "

";
            echo "错误原因:" . mysql_error() . "

";
           echo "
";
            echo "" . $message . "";
            echo "
";
            echo "
" . $sql . "
";
            $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)){
    die("upload files directory does not exist and creation failed");
   }
  }
    //建立txt日期文件 www.2cto.com
    if(!file_exists($file_path)){
     fopen($file_path,"w+");
     if(is_writable($file_path)){
      if(!$handle=fopen($file_path,'a')){
       echo "不能打开文件 $filename";
       exit;
      }
      if(!fwrite($handle,$error_content)){
       echo "不能写到文件 $filename";
       exit;
      }
      echo "——错误记录被保存!";
          fclose($handle);

     }else {
      echo "文件 $filename 不可写";
     }
    }else {
     if(is_writable($file_path)){
      if(!$handle=fopen($file_path,'a')){
        echo "不能打开文件 $filename";
                 exit;
      }
      if(!fwrite($handle,$error_content)){
       echo  "不能写入文件 $filename";
       exit;
      }
      echo "——错误记录被保存!";
              fclose($handle);
     }else {
      echo "文件 $filename 不可写";
     }
    }
   }
  echo "
"; 
  if ($this->is_error) {
     exit;
            }
        }
     echo "

";
echo "
";
echo "
";
}
//Release the result set
public function free(){
@mysql_free_result($this->result);
}
//Database selection
Public function select_db($db_database){
Return mysql_select_db($db_database);
}
//Query number of fields
Public function num_fields($table_name){
$this->query("select * from $table_name");
echo "
";
echo "Number of fields:".$total=mysql_num_fields($this->result);
for ($i=0;$i<$total;$i++){
Print_r(mysql_fetch_field($this->result,$i));
}
echo "";
echo "
";
}
//Get mysql server information
Public function mysql_server($num=''){
switch ($num){
case 1:
          return mysql_get_server_info();
         break;
case 2:
          return mysql_get_host_info();
         break;
case 3:
          return mysql_get_client_info();
         break;
case 4:
          return mysql_get_proto_info();
         break;
                                  default:
             return mysql_get_client_info();
}
}
public function __destruct(){
if(!empty($this->result)){
$this->free();
}
mysql_close($this->conn);
}
//Get the real ID address of the client
function getip() {
If (getenv("HTTP_CLIENT_IP") && strcasecmp(getenv("HTTP_CLIENT_IP"), "unknown")) {
               $ip = getenv("HTTP_CLIENT_IP");
          } else
If (getenv("HTTP_X_FORWARDED_FOR") &&strcasecmp(getenv("HTTP_X_FORWARDED_FOR"), "unknown")) {
                    $ip = getenv("HTTP_X_FORWARDED_FOR");
              } else
If (getenv("REMOTE_ADDR") && strcasecmp(getenv("REMOTE_ADDR"), "unknown")) {
                         $ip = getenv("REMOTE_ADDR");
                   } else
If (isset ($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] &&strcasecmp($_SERVER['REMOTE_ADDR'], "unknown")) {
$ip = $_SERVER['REMOTE_ADDR'];
                      } else {
                              $ip = "unknown";
                 }
         return ($ip);
}

}


?>

Excerpted from chaojie2009’s column

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/478368.htmlTechArticle?php /*** Database operation class * 2011/8/25 * kcj **/ class MyDB { private $db_host; //Database host name private $ db_user; //Database user name private $db_pwd; //Database password p...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn