1. Review
An example of PHP was learned in the previous article: a simple Article management system
2. Learning pointsThis article uses a singleton pattern to encapsulate an instantiated object class that implements MySQL3. Implementation class3.1 configuration file config.phpDefine constants: Host address, user name, password, database name.
<span style= "FONT-SIZE:18PX;" ><?phpdefine (' HOST ', ' localhost ');d efine (' USERNAME ', ' root ');d efine (' PASSWORD ', ');d efine (' DATABASE ', ' Test ');</span>
3.2 Implementation mysqlutil.phpinstantiate the mysql_connect () object with a singleton pattern and select the database to set the encoding set!
<span style= "FONT-SIZE:18PX;" ><?php//Singleton Mode Connection database//The constructor is marked as non-public//has a static member of the Save class instance//has an announcement method to access this instance require_once ' config.php '; class Db {// Save static member of instance private static $_instance;private static $_conn;//constituent function Private Function __construct () {}/** * Public entry Method */static pub Lic function getinstance () {//undetectable, re-instantiating object if (! (Self::$_instance instanceof Self)) {self::$_instance = new self ();} return self::$_instance;} /** * Connection Method * * @return resource */public function connect () {if (! self::$_conn) {self::$_conn = mysql_connect (HOST, USERNAME, PASSWORD),//self::$_conn=mysql_connect (' localhost ', ' root ', '), if (! Self::$_conn) {die (' Connection failed '). mysql _error ());} Select Database mysql_select_db (databases, self::$_conn);//Set CharSet mysql_query ("Set names UTF8", self::$_conn);} return self::$_conn;}? ></span>
3.3 Calling and using
<span style= "FONT-SIZE:18PX;" >//call $con=db::getinstance ()->connect ();//Query Statement $sql= ' SELECT * from User_info ';//execute, return result set $result=mysql_query ($ SQL, $con);//Added new array $arr3=array (); while ($row =mysql_fetch_row ($result)) {Array_push ($arr 3, $row);} </span>
4. SummaryWhen using, you need to configure the config.php file and call the time, do not forget to call the Connect () Method!
5.demo Downloadshttp://download.csdn.net/detail/lablenet/8995925
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
php-Singleton mode for MySQL instantiation object