Example of mysql encapsulation implemented by php

Source: Internet
Author: User

Php encapsulation mysql class

Copy codeThe Code is as follows:
<? Php

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 '<pre> ';
$ 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 "<br/> ";

$ SQL = "select * from stu ";
$ Arr = $ mysql-> getAll ($ SQL );

Print_r ($ arr );
?>

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.