PHP MySQL full database connection class _php tutorial

Source: Internet
Author: User
Tags mysql client mysql host mysql tutorial php mysql

PHP tutorial MySQL Tutorial full database Tutorial Connection class
*/
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; The result resource ID of the Execute Query command
Private $sql; SQL execution Statements
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, have security implications, default off
Private $is _error = false; If the error is immediately terminated, the default is true and the recommendation is not enabled because it is very distressing for the user to see nothing when there is a problem

/* Constructor function */
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 links
$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 is automatically printed when an error occurs
if ($this->show_error) {
$this->show_error ("Error SQL statement:", $this->sql);
}
} else {
$this->result = $result;
}
return $this->result;
}

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

/* Query server for all databases */
Separate the system database from the user database for a more intuitive display?
Public Function show_databases () {
$this->query ("Show Databases");
echo "Existing database:". $amount = $this->db_num_rows ($rs);
echo "
";
$i = 1;
while ($row = $this->fetch_array ($rs)) {
echo "$i $row [Database]";
echo "
";
$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;
}

/* 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 + +;
}
}

/*
Mysql_fetch_row () array $row [0], $row [1], $row [2]
Mysql_fetch_array () array $row [0] or $row [ID]
MYSQL_FETCH_ASSOC () array is case sensitive with $row->content fields
Mysql_fetch_object () object with $row[id], $row [content] field is case sensitive
*/

/* Get Results data */
Public Function Mysql_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);
}
}

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

Get a numeric index array, 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);
}

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

Simplified 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 succeeded! ');
}
}

Simplify inserting 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, ' Add success! ');
}
}

Simplified Modify 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*/from the previous insert operation
Public Function insert_id () {
return mysql_insert_id ();
}

Point to a data record that is determined
Public Function Db_data_seek ($id) {
if ($id > 0) {
$id = $id-1;
}
if (!@ mysql_data_seek ($this->result, $id)) {
$this->show_error ("SQL statement error:", "specified data is empty");
}
return $this->result;
}

Calculate result set bars based on 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);
}
}

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

Output Display SQL statement
Public Function show_error ($message = "", $sql = "") {
if (! $sql) {
echo "". $message. "";
echo "
";
} else {
echo "

";
echo " error message Tip:
";
echo "";
echo "";
echo "Error number: 12142";
echo "
";
echo "Error Reason:". Mysql_error (). "

";
echo "";
echo "". $message. "";
echo "";
echo "
" . $sql. "
";
$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"; Settings 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");
}
}

Create a txt date file
if (!file_exists ($file _path)) {

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

The first thing to determine is that the file exists and is writable
if (is_writable ($file _path)) {
Using Add mode to open $filename, 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 write to file $filename";
Exit
}

echo "File $filename write succeeded";

echo "--the error record is saved!";

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

} else {
The first thing to determine is that the file exists and is writable
if (is_writable ($file _path)) {
Using Add mode to open $filename, 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 write to file $filename";
Exit
}

echo "File $filename write succeeded";
echo "--the error record is saved!";

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

}
echo "
";
if ($this->is_error) {
Exit
}
}
echo "";
echo "

";

echo "
";
}

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 "
";
echo "Number of fields:". $total = Mysql_num_fields ($this->result);
echo "

";
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 (); 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 (); MySQL version information is obtained by default
}
}

destructor, automatically shuts down the database, garbage collection mechanism
Public Function __destruct () {
if (!empty ($this->result)) {
$this->free ();
}
Mysql_close ($this->conn);
}//function __destruct ();

/* Get 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 "Input illegal injection content! ";
Exit ();
} else {
return $sql _str;
}
}
function Checkurl () {//Check the antecedents
if (preg_replace ("/https tutorial?:/ /([^:/]+). */i "," 1 ", $_server[' Http_referer '])!== preg_replace ("/([^:]+). */"," 1 ", $_server[' Http_host ']) {
Header ("location:http://www.zhutiai.com");
Exit ();
}
}

}

http://www.bkjia.com/PHPjc/630762.html www.bkjia.com true http://www.bkjia.com/PHPjc/630762.html techarticle PHP tutorial MySQL tutorial full database Tutorial Connection class */class MySQL {private $db _host;//Database host private $db _user;//database user name private $db _pwd;//Database user Name Secret ...

  • 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.