This article describes how to implement mysql encapsulation in php. For more information, see
This article describes how to implement mysql encapsulation in php. For more information, see
Php encapsulation mysql class
The Code is as follows:
Class Mysql {
Private $ host;
Private $ user;
Private $ pwd;
Private $ dbName;
Private $ charset;
Private $ conn = null;
Public function _ construct (){
$ This-> host = 'localhost ';
$ This-> user = 'root ';
$ This-> pwd = 'root ';
$ This-> dbName = 'test ';
$ This-> connect ($ this-> host, $ this-> user, $ this-> pwd );
$ This-> switchDb ($ this-> dbName );
$ This-> setChar ($ this-> charset );
}
// Responsible for the link
Private function connect ($ h, $ u, $ p ){
$ Conn = mysql_connect ($ h, $ u, $ p );
$ This-> conn = $ conn;
}
// Switch the database
Public function switchDb ($ db ){
$ SQL = 'use'. $ db;
$ This-> query ($ SQL );
}
// Sets the character set.
Public function setChar ($ char ){
$ SQL = 'set names'. $ char;
$ This-> query ($ SQL );
}
// Sends SQL queries
Public function query ($ SQL ){
Return mysql_query ($ SQL, $ this-> conn );
}
// Obtain the select results of multiple rows and multiple columns
Public function getAll ($ SQL ){
$ List = array ();
$ Rs = $ this-> query ($ SQL );
If (! $ Rs ){
Return false;
}
While ($ row = mysql_fetch_assoc ($ rs )){
$ List [] = $ row;
}
Return $ list;
}
Public function getRow ($ SQL ){
$ Rs = $ this-> query ($ SQL );
If (! $ Rs ){
Return false;
}
Return mysql_fetch_assoc ($ rs );
}
Public function getOne ($ SQL ){
$ Rs = $ this-> query ($ SQL );
If (! $ Rs ){
Return false;
}
Return mysql_fetch_assoc ($ rs );
Return $ row [0];
}
Public function close (){
Mysql_close ($ this-> conn );
}
}
Echo'
';
$ Mysql = new Mysql ();
Print_r ($ mysql );$ SQL = "insert into stu values (4, 'wangw', '123 ')";
If ($ mysql-> query ($ SQL )){
Echo "query successful ";
} Else {
Echo "failed ";
}
Echo"
";
$ SQL = "select * from stu ";
$ Arr = $ mysql-> getAll ($ SQL );
Print_r ($ arr );
?>
,