Home Backend Development PHP Tutorial mysql operation class_PHP tutorial

mysql operation class_PHP tutorial

Jul 13, 2016 pm 05:49 PM
class host mysql php private host operate database machine kind

/**
* 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 of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

The Future of PHP: Adaptations and Innovations The Future of PHP: Adaptations and Innovations Apr 11, 2025 am 12:01 AM

The future of PHP will be achieved by adapting to new technology trends and introducing innovative features: 1) Adapting to cloud computing, containerization and microservice architectures, supporting Docker and Kubernetes; 2) introducing JIT compilers and enumeration types to improve performance and data processing efficiency; 3) Continuously optimize performance and promote best practices.

How to open phpmyadmin How to open phpmyadmin Apr 10, 2025 pm 10:51 PM

You can open phpMyAdmin through the following steps: 1. Log in to the website control panel; 2. Find and click the phpMyAdmin icon; 3. Enter MySQL credentials; 4. Click "Login".

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

MySQL: An Introduction to the World's Most Popular Database MySQL: An Introduction to the World's Most Popular Database Apr 12, 2025 am 12:18 AM

MySQL is an open source relational database management system, mainly used to store and retrieve data quickly and reliably. Its working principle includes client requests, query resolution, execution of queries and return results. Examples of usage include creating tables, inserting and querying data, and advanced features such as JOIN operations. Common errors involve SQL syntax, data types, and permissions, and optimization suggestions include the use of indexes, optimized queries, and partitioning of tables.

How to use single threaded redis How to use single threaded redis Apr 10, 2025 pm 07:12 PM

Redis uses a single threaded architecture to provide high performance, simplicity, and consistency. It utilizes I/O multiplexing, event loops, non-blocking I/O, and shared memory to improve concurrency, but with limitations of concurrency limitations, single point of failure, and unsuitable for write-intensive workloads.

Why Use MySQL? Benefits and Advantages Why Use MySQL? Benefits and Advantages Apr 12, 2025 am 12:17 AM

MySQL is chosen for its performance, reliability, ease of use, and community support. 1.MySQL provides efficient data storage and retrieval functions, supporting multiple data types and advanced query operations. 2. Adopt client-server architecture and multiple storage engines to support transaction and query optimization. 3. Easy to use, supports a variety of operating systems and programming languages. 4. Have strong community support and provide rich resources and solutions.

PHP's Current Status: A Look at Web Development Trends PHP's Current Status: A Look at Web Development Trends Apr 13, 2025 am 12:20 AM

PHP remains important in modern web development, especially in content management and e-commerce platforms. 1) PHP has a rich ecosystem and strong framework support, such as Laravel and Symfony. 2) Performance optimization can be achieved through OPcache and Nginx. 3) PHP8.0 introduces JIT compiler to improve performance. 4) Cloud-native applications are deployed through Docker and Kubernetes to improve flexibility and scalability.

PHP: Is It Dying or Simply Adapting? PHP: Is It Dying or Simply Adapting? Apr 11, 2025 am 12:13 AM

PHP is not dying, but constantly adapting and evolving. 1) PHP has undergone multiple version iterations since 1994 to adapt to new technology trends. 2) It is currently widely used in e-commerce, content management systems and other fields. 3) PHP8 introduces JIT compiler and other functions to improve performance and modernization. 4) Use OPcache and follow PSR-12 standards to optimize performance and code quality.

See all articles