PHP MySQL Encapsulation class instance code _php instance

Source: Internet
Author: User

Nonsense is not much to say, the specific code looks like this:

<?php class MySQL {private $db _host;//Database host private $db _user;//database user name private $db _pwd;//database username password Private $db _datab Ase Database name private $conn;
database connection identification; Private $result; Execute the query command results resource identification private $sql; SQL execution Statement private $row; Number of entries returned private $coding; Database encoding, gbk,utf8,gb2312 private $bulletin = true; Whether to turn on error logging private $show _error = false; Test phase, show all errors, with security risks, the default shutdown private $is _error = false; Find out if the error terminates immediately, default true, and is not recommended because the user cannot see anything when there is a problem./* 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, etc. any SQL statement/Public Function query ($sql) {if ($sql = = "") {$this->show_error ("SQL statement error:", "SQL query Language
Sentence is empty ");
} $this->sql = $sql;
$result = mysql_query ($this->sql, $this->conn); if (! $result) {//is used in debugging, the SQL statement automatically prints if ($this->show_error) {$this->show_error ("Error SQL statement:", $this->sql);}
else {$this->result = $result;} return $this->result; } * * Create add new database/Public function create_database ($database _name) {$database = $database _name; $sqlDatabase = ' Create Datab Ase '.
$database;
$this->query ($sqlDatabase);
* * Query server all databases////separate system database from user database, more intuitive display? 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 an array of all database name public function databases () {$rsPtr = Mysql_list_dbs ($this->conn) in the host, $i = 0; $cnt = mysql_num_rows ($r
SPTR);
while ($i < $cnt) {$rs [] = Mysql_db_name ($rsPtr, $i); $i + +;} return $rs; } * * All tables under 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 () AR Ray uses $row->content field case sensitive mysql_fetch_object () object with $row[id], $row [content] field case sensitive/* Get result data */Public function M Ysql_result_li () {return mysql_result ($STR);}/* Get Recordset, get array-Index and association, use $row[' content '] */Public Function Fetch_array ($ Resultt= "") {if ($resultt <> ""){return mysql_fetch_array ($RESULTT);}
else{return mysql_fetch_array ($this->result);} Gets the associative array, using the $row[' field name '] public function Fetch_assoc () {return Mysql_fetch_assoc ($this->result);}//Get an array of numeric indices, using $row [0], $row [1], $row [2] public Function Fetch_row () {return mysql_fetch_row ($this->result);}//Get an array of objects, using $row-> Content Public Function Fetch_object () {return mysql_fetch_object ($this->result);}//Simplified query select public Function find All ($table) {$this->query ("SELECT * from $table")}//Simplified query Select Public Function Select ($table, $columnName = "*", $c Ondition = ', $debug = ') {$condition = $condition? ' Where '.
$condition: NULL; if ($debug) {echo ' select $columnName from $table $condition ';} else {$this->query ("Select $columnName from $table $
Condition "); }//Simplify deleting del public function Delete ($table, $condition, $url = ') {if ($this->query ("Delete from $table WHERE $condi tion ")) {if (!empty ($url)) $this->get_admin_msg ($url, ' Delete succeeded!
'); }//Simplify inserting insert PuBlic function Insert ($table, $columnName, $value, $url = ') {if ($this->query ("INSERT into $table ($columnName) value S ($value)) {if (!empty ($url)) $this->get_admin_msg ($url, ' Add success!
'); }//Simplified Modify update public Function update ($table, $mod _content, $condition, $url = ') {//echo update $table SET $mod _cont ent WHERE $condition ";
Exit (); if ($this->query ("UPDATE $table SET $mod _content WHERE $condition")) {if (!empty ($url)) $this->get_admin_msg ($url
); }/* To obtain the id*/public function insert_id () {return mysql_insert_id () that was generated by the previous INSERT operation, and//point to a determined data logging public function Db_d Ata_seek ($id) {if ($id > 0) {$id = $id-1;} if (!@ Mysql_data_seek ($this->result, $id)) {$this->show_error ("S
QL Statement error: "," specified data is empty ");
return $this->result; ////Based on select query Results the number of result set bars 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);} According to the Insert, the Update,delete execution result gets the number of rows public function db_affected_rows () {return mysql_affected_rows ().}//Output shows SQL statement public function Show_error ($message = "", $sql = "") {if (! $sql) {echo "<font color= ' Red ' >". $message.
"</font>";
echo "<br/>"; else {echo ' <fieldset> '; Echo ' <legend> error message hint: </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. "\r\n$this->sql". "\ r \ n Customer IP: $ip". "\ r \ n time: $time".
"\r\n\r\n";
$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 folder if (!file_exists ($file)) {if (!mkdir ($file, 0777)) {//The default mode is 0777, which means the maximum possible access die ("Upload files D
Irectory does not exist and creation failed "); ///Establish TXT date file if (!file_exists ($file _path)) {//echo "Build date File"; fopen ($file _path, "w+");///First determine if the file exists and can write if (is_writable ( 
$file _path)) {//$filename opened with Add mode, 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!";
Closes the file fclose ($handle); else {echo ' file $filename not writable ';}} else {//first to determine the existence of the file and to write if (is_writable ($file _path)) {//Open $filename using Add mode, the file pointer will be at the beginning of the file
if (! $handle = fopen ($file _path, ' a ')) {echo cannot open file $filename; exit;//write $somecontent to the file we open.
if (!fwrite ($handle, $error _content)) {echo cannot be written to the file $filename "; exit;}//echo" File $filename write Success ";
echo "--Error Record saved!";
Closes the file fclose ($handle);
else {echo ' file $filename not writable ';}}
echo "<br/>";
if ($this->is_error) {exit;}}
echo "</div>";
echo "</fieldset>";
echo "<br/>"; //Release result set public function free () {@ mysql_free_result ($this->result);}//Database Select Public Function select_db ($db _database {return mysql_select_db ($db _database);}//query field quantity 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 the MySQL protocol information break; Default:return Mysql_get_client_info (); MySQL version info}//destructor, automatically shutdown database, garbage collection mechanism public Function __destruct () {if (!empty ($this->result)) {$this->free ()
;
} mysql_close ($this->conn);
}//function __destruct (); /* Obtain the client's true 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 ") && s TRCASECMP (getenv ("REMOTE_ADDR"), "Unknown")) {$ip = getenv ("REMOTE_ADDR");} else if (Isset ($_server[' remote_addr ']) &A mp;& $_server[' REMOte_addr '] && strcasecmp ($_server[' remote_addr '], "unknown")) {$ip = $_server[' remote_addr '];} else {$ip = "unk
Nown ";
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 input illegally injected content!
";
Exit ();
else {return $sql _str;}} function Checkurl () {//Check routing if (Preg_replace ("/https?:\ /\/([^\:\/]+). */i "," \\1 ", $_server[' Http_referer '])!== preg_replace ("/([^\:]+). * "," \\1 ", $_server[' Http_host '])
{Header ("location:http://www.dareng.com"); exit ();} }}?>

The above is a small set to introduce PHP MySQL encapsulation Class example code, I hope to help you, if you have any questions welcome to my message, small series will promptly reply to everyone, here also thank you for your support cloud Habitat community site!

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.