PHP implementation MySQL Encapsulation class example _php instance

Source: Internet
Author: User

PHP Encapsulation MySQL Class

Copy Code code 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 links
Private function Connect ($h, $u, $p) {
$conn = mysql_connect ($h, $u, $p);
$this->conn = $conn;
}

Responsible for switching the database
Public Function Switchdb ($db) {
$sql = ' use '. $db;
$this->query ($sql);
}

Responsible for setting the character set
Public Function SetChar ($char) {
$sql = ' Set names '. $char;
$this->query ($sql);
}

Responsible for sending SQL queries
Public Function Query ($sql) {
Return mysql_query ($sql, $this->conn);
}

Select results that are responsible for fetching multiple rows and 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, ' Wangwu ', ' 99998 ')";

if ($mysql->query ($sql)) {
echo "Query succeeded";
}else {
echo "Failed";
}

echo "<br/>";

$sql = "SELECT * from Stu";
$arr = $mysql->getall ($sql);

Print_r ($arr);
?>

Related Article

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.