The classic MySQL database connection operation class

Source: Internet
Author: User
Tags garbage collection mysql client mysql host mysql version create database mysql database
The code is as follows Copy Code

<?php
Class MySQL {
Private $db _host; Database Host
Private $db _user; Database user Name
Private $db _pwd; Database User name password
Private $db _database; Database name
Private $conn; database connection identification;
Private $result; To perform the result resource identification of the query command
Private $sql; SQL Execution Statement
Private $row; Number of entries returned
Private $coding; Database coding, gbk,utf8,gb2312
Private $bulletin = true; Whether to turn on error logging
Private $show _error = true; Test phase, show all errors, have security implications, default shutdown
Private $is _error = false; Find out if the error terminates immediately, default true, recommended not enabled, because the user can see nothing when there is a problem is very distressed

/* Constructor/*
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 ();
}

/* Database Connection * *
Public Function connect () {
if ($this->conn = = "Pconn") {
Permanent link
$this->conn = mysql_pconnect ($this->db_host, $this->db_user, $this->db_pwd);
} else {
Even if the link
$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);
}
}
mysql_query ("SET NAMES $this->coding");
}

/* Database execution statement, executable query add modify delete, and so on any SQL statement * *
Public Function Query ($sql) {
if ($sql = = "") {
$this->show_error ("SQL statement error:", "SQL query statement is empty");
}
$this->sql = $sql;

$result = mysql_query ($this->sql, $this->conn);

if (! $result) {
Used in debugging, the SQL statement automatically prints when an error occurs
if ($this->show_error) {
$this->show_error ("Error SQL statement:", $this->sql);
}
} else {
$this->result = $result;
}
return $this->result;
}

/* Create add a new database * *
Public Function Create_database ($database _name) {
$database = $database _name;
$sqlDatabase = ' Create database '. $database;
$this->query ($sqlDatabase);
}

/* Query Server all databases * *
Separate the system database from the user database and display it more intuitively?
Public Function show_databases () {
$this->query ("Show Databases");
echo "Existing database:". $amount = $this->db_num_rows ($rs);
echo "<br/>";
$i = 1;
while ($row = $this->fetch_array ($rs)) {
echo "$i $row [Database]";
echo "<br/>";
$i + +;
}
}

Returns all database names in the host as 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;
}

* * All tables under the query database * *
Public Function Show_tables ($database _name) {
$this->query ("Show Tables");
echo "Existing database:". $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] or $row [ID]
MYSQL_FETCH_ASSOC () array is sensitive with $row->content field case
Mysql_fetch_object () object with $row[id], $row [content] field case sensitive
*/

* * Obtain the result data * *
Public Function Mysql_result_li () {
Return mysql_result ($STR);
}

/* Get the Recordset, get the array-Index and association, use $row[' content '] * *

Public Function Fetch_array () {
Return mysql_fetch_array ($this->result);
}

Public Function Fetch_array ($query) {
return mysql_fetch_array ($query);
// }

Get associative array, using $row[' field name ']
Public Function Fetch_assoc () {
Return Mysql_fetch_assoc ($this->result);
}

Gets an array of numeric indices, using $row[0], $row [1], $row [2]
Public Function Fetch_row () {
Return mysql_fetch_row ($this->result);
}

Gets an array of objects, using the $row->content
Public Function Fetch_object () {
Return Mysql_fetch_object ($this->result);
}

Simplify Query Select
Public function FindAll ($table) {
$this->query ("SELECT * from $table");
}

Simplify 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 Delete del
Public Function Delete ($table, $condition, $url = ') {
if ($this->query ("DELETE from $table WHERE $condition)") {
if (!empty ($url))
$this->get_admin_msg ($url, ' delete success! ');
}
}

Simplify Insert Inserts
Public Function Insert ($table, $columnName, $value, $url = ') {
if ($this->query (INSERT into $table ($columnName) VALUES ($value)) {
if (!empty ($url))
$this->get_admin_msg ($url, ' Add success! ');
}
}

Simplify modification update
Public 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);
}
}

/* Get the id*/generated by the previous INSERT operation
Public Function insert_id () {
return mysql_insert_id ();
}

 //point to a determined data record
 public function Db_data_seek ($id) {
  if ($id > 0) {
  & nbsp. $id = $id-1;
  }
  if (!@ mysql_data_seek ($this->result, $id)) {
    $this->show_error (" SQL statement error: "," specified data is empty ");
  }
  return $this->result;
 }

Calculate the number of result set bars based on the select query results
/* Public Function db_num_rows () {
if ($this->result = = null) {
if ($this->show_error) {
$this->show_error ("SQL statement error", "temporarily empty, no content!") ");
}
} else {
Return mysql_num_rows ($this->result);
}
}*/
Public Function Db_num_rows ($result) {
if ($result ==null) {
if ($this->show_error) {
$this->show_error ("SQL statement error", "temporarily empty, no content!") ");
}
}else{
Return mysql_num_rows ($result);
}
}

Number of rows affected based on Insert,update,delete execution results
Public Function db_affected_rows () {
return Mysql_affected_rows ();
}

Output shows SQL statements
Public Function show_error ($message = "", $sql = "") {
if (! $sql) {
echo "<font color= ' Red ' >". $message. "</font>";
echo "<br/>";
} else {
echo "<fieldset>";
echo "<legend> error message Tip: </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 ' > Error number:12142</font>";
echo "</div><br/>";
echo "Error Reason:". 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. "Rn$this->sql". "RN Client IP: $ip". "RN Time: $time". "Rnrn";

$server _date = Date ("y-m-d");
$filename = $server _date. ". txt";
$file _path = "error/". $filename;
$error _content = $message;
$error _content= "Wrong database, can not link";
$file = "Error"; Set File Save Directory

Create a folder
if (!file_exists ($file)) {
if (!mkdir ($file, 0777)) {
The default mode is 0777, which means the maximum possible access rights
Die ("Upload files directory does not exist and creation failed");
}
}

Set up txt date file
if (!file_exists ($file _path)) {

echo "Build date File";
fopen ($file _path, "w+");

First, make sure that the file exists and can be written
if (is_writable ($file _path)) {
Open $filename with Add mode, and the file pointer will be at the beginning of the file
if (! $handle = fopen ($file _path, ' a ')) {
echo "Cannot open file $filename";
Exit
}

Write the $somecontent to the file we opened.
if (!fwrite ($handle, $error _content)) {
echo "cannot be written to the file $filename";
Exit
}

echo "File $filename write Success";

echo "--Error Record saved!";

Close File
Fclose ($handle);
} else {
echo "File $filename not writable";
}

} else {
First, make sure that the file exists and can be written
if (is_writable ($file _path)) {
Open $filename with Add mode, and the file pointer will be at the beginning of the file
if (! $handle = fopen ($file _path, ' a ')) {
echo "Cannot open file $filename";
Exit
}

Write the $somecontent to the file we opened.
if (!fwrite ($handle, $error _content)) {
echo "cannot be written to the file $filename";
Exit
}

echo "File $filename write Success";
echo "--Error Record saved!";

Close File
Fclose ($handle);
} else {
echo "File $filename not writable";
}
}

}
echo "<br/>";
if ($this->is_error) {
Exit
}
}
echo "</div>";
echo "</fieldset>";

echo "<br/>";
}

Releasing 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);
}

Number of query fields
Public Function Num_fields ($table _name) {
Return Mysql_num_fields ($this->result);
$this->query ("select * from $table _name");
echo "<br/>";
echo number of fields:. $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/>";
}

Get MySQL Server information
Public Function mysql_server ($num = ' ") {
Switch ($num) {
Case 1:
return Mysql_get_server_info (); MySQL Server information
Break

Case 2:
return Mysql_get_host_info (); Get MySQL host Information
Break

Case 3:
return Mysql_get_client_info (); Get MySQL Client Information
Break

Case 4:
return Mysql_get_proto_info (); Get MySQL protocol Information
Break

Default:
return Mysql_get_client_info (); Default get MySQL version information
}
}

destructor, automatic shutdown of database, garbage collection mechanism
Public Function __destruct () {
if (!empty ($this->result)) {
$this->free ();
}
Mysql_close ($this->conn);
}//function __destruct ();

/* Obtain the client's real IP address. *
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);
}
function Inject_check ($sql _str) {//Prevent injection
$check = eregi (' select|insert|update|delete| ' | /*|*|.. /|. /|union|into|load_file|outfile ', $sql _str);
if ($check) {
echo "Enter illegal injection content!" ";
Exit ();
} else {
return $sql _str;
}
}
function Checkurl () {//Check antecedents
if (Preg_replace ("/https?:/ /([^:/]+). */i "," \1 ", $_server[' Http_referer '])!== preg_replace ("/([^:]+). * "," \1 ", $_server[' Http_host ']) {
Header ("Location:http://www.111cn.net");
Exit ();
}
}
function Htmtocode ($content) {
$content = Str_replace ("n", "<br>", Str_replace ("", "&nbsp;", $content));
return $content;
}

}
$db =new MySQL ("localhost", "root", "" "," Messages "," "", "GBK");
?>

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.