Each time you operate the MySQL database, you have to connect, select the database and other repetitive actions, why not encapsulate it into a class? It's easy to do that.
Maybe you can say that it's OK to write a function. However, writing a class encapsulates some information about the database, such as the database name, database host, database user, and password. In this way, in a function that needs to operate MySQL, it is not necessary to pass this information, directly into a MySQL object can be, is not very convenient?
Well, here's the code:
Download: http://down.qiannao.com/space/file/pgtimes/share/2011/3/8/mysqlobj.php/.page
Db_name = $DN; $this->db_user = $du; $this->db_pawd = $DP; $this->db_host = $DH; $this->db_charset = $DC; $this->db_collate = $do; }/** destructor */function __destruct () {if ($this->iscon) $this->closecon ();}/** create connection, no return value */function Newcon () {if (! $this->iscon) {$this->link = mysql_connect ($this->db_host, $this->db_user, $this->db_pawd) or Die ("Cannot create a data connection
". Mysql_error ()); mysql_query ("SET NAMES {$this->db_charset}"); $this->iscon = true; }}/** closes the connection with no return value */function Closecon () {if ($this->iscon) {mysql_close ($this->link); $this->iscon = false;} /** Execute SQL command, input parameters: SQL statement, return value: Execution result */function Execute ($sql) {if (! $this->iscon) $this->newcon (); $db _selected = Mys ql_select_db ($this->db_name, $this->link) or Die ("Open database failed
". Mysql_error ($this->link)); $result = mysql_query ($sql, $this->link); return $result; }}?>
can also point me to download;
You should create a MySQL object as follows
Use as follows:
Newcon (); New Connection $sql = "SELECT * FROM table"; SQL statement $result = $mysql->execute ($sql); Executes the SQL query and returns the result $mysql->closecon (); Close Connection?>
Be sure to close the connection before the next Newcon ()!
Therefore, please close the connection (Closecon ()) in time after each SQL query execution!
Because every time we create a MySQL object to pass in the database of some information, and we write the site when the information is basically unchanged, so we can write a function
After the operation and information of MySQL database is encapsulated into a class, there are many benefits, and this benefit will be very much reflected in my later articles.
Transferred from: Http://blog.abreto.net/oa/php-mysql-class