English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

PHP MySQL Encapsulation Class Example Code

No more废话 to say, the specific code is as follows:

<?php
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 identifier;
private $result; //Resource identifier of the result of executing the query command
private $sql; //SQL execution statement
private $row; //Number of entries returned
private $coding; //Database encoding, GBK, UTF8,gb2312
private $bulletin = true; //Whether to enable error recording
private $show_error = false; //Show all errors in the test phase, has security risks, default is off
private $is_error = false; //Whether to terminate immediately when an error is found, default true, it is recommended not to enable because it is very annoying for users 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);
}
//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 is not available:", $this->db_database);
}
}
mysql_query("SET NAMES $this->coding");
}
/*Execute database statements, can execute any SQL statement such as query, add, modify, delete, etc.*/
public function query($sql) {
if ($sql == "") {
$this->show_error("SQL statement error:", "The SQL query statement is empty");
}
$this->sql = $sql;
$result = mysql_query($this->sql, $this->conn);
if (!$result) {
//Used for debugging, it will automatically print out the SQL statement when an error occurs in the SQL statement
if ($this->show_error) {
$this->show_error("Error SQL statement:", $this->sql);
}
}
$this->result = $result;
}
return $this->result;
}
/*Create 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 system databases and user databases, making the display more intuitive?
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++;
}
}
//Return all database names on the host in array form
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 "<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 using $row->content field is case-sensitive
mysql_fetch_object() object using $row[id], $row[content] field is case-sensitive
*/
/*Get the result data*/
public function mysql_result_li() {
return mysql_result($str);
}
/*Get the record set, obtain an array-Index and association, using $row['content'] */
public function fetch_array($resultt="") {
if($resultt<>"{")
return mysql_fetch_array($resultt);}}
} else {
return mysql_fetch_array($this->result);
}
}
//Get associated array, using $row['field name']
public function fetch_assoc() {
return mysql_fetch_assoc($this->result);
}
//Get numeric index array, using $row[0], $row[1], $row[2]
public function fetch_row() {
return mysql_fetch_row($this->result);
}
//Get object array, using $row->content
public function fetch_Object() {
return mysql_fetch_object($this->result);
}
//Simplified Query
public function findall($table) {
$this-query("SELECT * FROM $table");
}
//Simplified Query
public function select($table, $columnName = "*", $condition = '', $debug = '') {
$condition = $condition &63; 'Where' . $condition : NULL;
if ($debug) {
echo "SELECT $columnName FROM $table $condition";
}
$this-query("SELECT $columnName FROM $table $condition");
}
}
//Simplified Deletion
public function delete($table, $condition, $url = '') {
if ($this-query("DELETE FROM $table WHERE $condition")) {
if (!empty ($url))
$this-Get_admin_msg($url, 'Deleted successfully!');
}
}
//Simplified Insertion
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!');
}
}
//Simplify the update modification
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);
}
}
/*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 is incorrect:", "The specified data is empty");
}
return $this->result;
}
// Calculate the number of rows in the result set based on the select query result
public function db_num_rows() {
if ($this->result == null) {
if ($this->show_error) {
$this->show_error("SQL statement error", "Currently empty, no content!");
}
}
return mysql_num_rows($this->result);
}
}
// Obtain the number of affected rows based on the results of insert, update, delete operations
public function db_affected_rows() {
return mysql_affected_rows();
}
//Output the displayed SQL statement
public function show_error($message = "", $sql = "") {
if (!$sql) {
echo "<font color='red'>" . $message . "<"/font>";
echo "<br />";
}
echo "<fieldset>";
echo "<legend>Error information prompt:</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\nCustomer IP:$ip" . "\r\nTime :$time" . "\r\n\r\n";
$server_date = date("Y-m-d");
$filename = $server_date . ".txt";
$file_path = "error/" . $filename;
$error_content = $message;
//$error_content="Incorrect database, cannot link";
$file = "error"; //Set file save directory
//Create folder
if (!file_exists($file)) {
if (!mkdir($file, 0777)) {
//The default mode is 0777means the maximum possible access rights
die("upload files directory does not exist and creation failed");
}
}
//Create txt date file
if (!file_exists($file_path)) {
//echo "Create date file";
fopen($file_path, "w+");
//Firstly, make sure the file exists and is writable
if (is_writable($file_path)) {
//Open $filename in append 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 have opened.
if (!fwrite($handle, $error_content)) {
echo "Cannot write to file $filename";
exit;
}
//echo "File $filename write success";
echo "——Error log is saved!";
//Close file
fclose($handle);
}
echo "File $filename is not writable";
}
}
//Firstly, make sure the file exists and is writable
if (is_writable($file_path)) {
//Open $filename in append 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 have opened.
if (!fwrite($handle, $error_content)) {
echo "Cannot write to file $filename";
exit;
}
//echo "File $filename write success";
echo "——Error log is saved!";
//Close file
fclose($handle);
}
echo "File $filename is 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 selection
public function select_db($db_database) {
return mysql_select_db($db_database);
}
//Query field count
public function num_fields($table_name) {
//return mysql_num_fields($this->result);
$this->query("select * from $table_name");
echo "<br />";
echo "字段数:" . $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(); //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(); //Default to obtain MySQL version information
}
}
//Destructor, automatically close the database, garbage collection mechanism
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");
}
if (getenv("HTTP_X_FORWARDED_FOR") && strcasecmp(getenv("HTTP_X_FORWARDED_FOR"), "unknown")) {
$ip = getenv("HTTP_X_FORWARDED_FOR");
}
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);
}
function inject_check($sql_str) { //Prevent Injection
$check = eregi('select|insert|update|delete|\'|\/\*|\*|\.\.\/|\.\/|union|into|load_file|outfile', $sql_str);
if ($check) {
echo "Illegal injection content input!";
exit ();
}
return $sql_str;
}
}
function checkurl() { //Check Origin
if (preg_replace("/https?:\/\/([^\:\/]+).*/i", "\\1", $_SERVER['HTTP_REFERER']) !== preg_replace("/([^\:]+).*/", "\\1", $_SERVER['HTTP_HOST'])) {
header("Location: http://www.dareng.com");
exit();
}
}
}
?>

The above-mentioned is the example code of php mysql encapsulation class introduced by the editor for everyone. I hope it will be helpful to everyone. If you have any questions, please leave a message for me, and I will reply to everyone in time. At the same time, I also thank everyone for their support of the Yanaogao tutorial website!

Declaration: The content of this article is from the Internet, and the copyright belongs to the original author. The content is contributed and uploaded by Internet users spontaneously. This website does not own the copyright, has not been manually edited, and does not assume relevant legal liability. If you find any content suspected of copyright infringement, please send an email to notice#w3Please send an email to codebox.com (replace # with @ when sending an email) to report violations, and provide relevant evidence. Once verified, this site will immediately delete the infringing content.

You May Also Like