In-depth understanding of php's MySQL connection class _ PHP Tutorial

Source: Internet
Author: User
Tags mysql host
Deeply understand the MySQL connection class of php. I accidentally found such a Mysql connection class on my computer, and I can't remember where to add it to my favorites. paste it. The following methods, such as show_databases and show_tables..., used a bunch of ec and accidentally found such a Mysql connection class on the computer. I don't remember where to add it to my favorites. paste it.
Next several show_databases and show_tables .... and other methods use a bunch of echo, it seems that I have never liked to directly use the output statement in the class method, but this is just to list the database and table name, you can also set a default value for the constructor parameter.

The code is as follows:


/*
* Filename: mysql database connection class
*/
Class mysql {
Private $ db_host; // database host
Private $ db_user; // database username
Private $ db_pwd; // database username and password
Private $ db_database; // database name
Private $ conn; // Database Connection ID;
Private $ result; // result resource ID for executing the query command
Private $ SQL; // SQL execution statement
Private $ row; // number of returned entries
Private $ coding; // database encoding, GBK, UTF8, gb2312
Private $ bulletin = true; // whether to enable error records
Private $ show_error = true; // in the test phase, all errors are displayed, which has security risks and is disabled by default.
Private $ is_error = false; // determines whether an error is terminated immediately. the default value is true. we recommend that you do not enable the error because it is annoying to see nothing 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 {
// Instant 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 statements: execute queries, add, modify, delete, and other SQL statements */
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 during debugging. the SQL statement is automatically printed when an error occurs.
If ($ this-> show_error ){
$ This-> show_error ("incorrect 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 all databases on the server */
// Separate the system database from the user database for more intuitive display?
Public function show_databases (){
$ Rs = $ 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 the names of all databases on the host in 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 in the database */
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 the $ row-> content field
Mysql_fetch_object () object is case sensitive with $ row [id] and $ row [content] Fields
*/
/* Obtain result data */
Public function mysql_result_li ()
{
Return mysql_result ($ str );
}
/* Obtain the record set and array-index and association. use $ row ['content'] */
Public function fetch_array ()
{
Return mysql_fetch_array ($ this-> result );
}
// Obtain the joined array, using $ row ['Field name']
Public function fetch_assoc ()
{
Return mysql_fetch_assoc ($ this-> result );
}
// Obtain the numeric index array, using $ row [0], $ row [1], $ row [2]
Public function fetch_row ()
{
Return mysql_fetch_row ($ this-> result );
}
// Obtain the object array using $ 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)
{
If ($ columnName = ""){
$ ColumnName = "*";
}
$ This-> query ("SELECT $ columnName FROM $ table $ condition ");
}
// Simplify del deletion
Public function delete ($ table, $ condition ){
$ This-> query ("delete from $ table WHERE $ condition ");
}
// Simplify insert
Public function insert ($ table, $ columnName, $ value ){
$ This-> query ("insert into $ table ($ columnName) VALUES ($ value )");
}
// Simplify update modification
Public function update ($ table, $ mod_content, $ condition ){
$ This-> query ("UPDATE $ table SET $ mod_content WHERE $ condition ");
}
/* Obtain the ID generated by the previous INSERT operation */
Public function insert_id (){
Return mysql_insert_id ();
}
// Point to a specific data record
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:", "the specified data is empty ");
}
Return $ this-> result;
}
// Calculate the number of result sets 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 );
}
}
// Obtain the number of affected rows based on insert, update, and delete execution results
Public function db_affected_rows (){
Return mysql_affected_rows ();
}
// Output the SQL statement
Public function show_error ($ message = "", $ SQL = ""){
If (! $ SQL ){
Echo "". $ message ."";
Echo"
";
} Else {
Echo"

";
Echo" Error message:
";
Echo"

";
Echo"

";
Echo "error code: 12142 ";
Echo"


";
Echo "error cause:". 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 customer IP address: $ ip ". "/r/n time: $ time ". "/r/n ";
$ Server_date = date ("Y-m-d ");
$ Filename = $ server_date. ". txt ";
$ File_path = "error/". $ filename;
$ Error_content = $ message;
// $ Error_content = "wrong database, cannot be connected ";
$ File = "error"; // sets the file storage directory.
// Create a folder
If (! File_exists ($ file )){
If (! Mkdir ($ file, 0777 )){
// The default mode is 0777, which means the maximum possible access.
Die ("upload files directory does not exist and creation failed ");
}
}
// Create a txt date file
If (! File_exists ($ file_path )){
// Echo "create date file ";
Fopen ($ file_path, "w + ");
// First, make sure that the file exists and is writable.
If (is_writable ($ file_path ))
{
// Open $ filename in add mode. the file pointer will start with the file
If (! $ Handle = fopen ($ file_path, 'A '))
{
Echo "the file $ filename cannot be opened ";
Exit;
}
// Write $ somecontent to the open file.
If (! Fwrite ($ handle, $ error_content ))
{
Echo "cannot be written to file $ filename ";
Exit;
}
// Echo "file $ filename written successfully ";
Echo "-- the error record is saved! ";
// Close the file
Fclose ($ handle );
} Else {
Echo "file $ filename cannot be written ";
}
} Else {
// First, make sure that the file exists and is writable.
If (is_writable ($ file_path ))
{
// Open $ filename in add mode. the file pointer will start with the file
If (! $ Handle = fopen ($ file_path, 'A '))
{
Echo "the file $ filename cannot be opened ";
Exit;
}
// Write $ somecontent to the open file.
If (! Fwrite ($ handle, $ error_content ))
{
Echo "cannot be written to file $ filename ";
Exit;
}
// Echo "file $ filename written successfully ";
Echo "-- the error record is saved! ";
// Close the file
Fclose ($ handle );
} Else {
Echo "file $ filename cannot be written ";
}
}
}
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 the number of 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"
";
}
// Obtain 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 (); // Obtain MySQL host information
Break;
Case 3:
Return mysql_get_client_info (); // Obtain MySQL client information
Break;
Case 4:
Return mysql_get_proto_info (); // Obtain MySQL protocol information
Break;
Default:
Return mysql_get_client_info (); // Obtain the mysql version by default.
}
}
// Destructor, which automatically closes the database and recycles garbage
Public function _ destruct ()
{
If (! Empty ($ this-> result )){
$ This-> free ();
}
Mysql_close ($ this-> conn );
} // Function _ destruct ();
/* Obtain the real IP 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 );
}
}
?>


Bytes. The following show_databases and show_tables... methods use a bunch of ec...

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.