PHP封裝mysqli基于面向?qū)ο蟮膍ysql數(shù)據(jù)庫操作類與用法示例
本文實例講述了PHP封裝mysqli基于面向?qū)ο蟮膍ysql數(shù)據(jù)庫操作與用法。分享給大家供大家參考,具體如下:
首先封裝好mysql類
mysql.php
<?php
class Mysql{
private static $host="localhost";
private static $user="root";
private static $password="123456";
private static $dbName="test"; //數(shù)據(jù)庫名
private static $charset="utf8"; //字符編碼
private static $port="3306"; //端口號
private $conn=null;
function __construct(){
$this->conn=new mysqli(self::$host,self::$user,self::$password,self::$dbName,self::$port);
if(!$this->conn)
{
die("數(shù)據(jù)庫連接失??!".$this->conn->connect_error);
}else{
echo "連接成功!";
}
$this->conn->query("set names ".self::$charset);
}
//執(zhí)行sql語句
function sql($sql){
$res=$this->conn->query($sql);
if(!$res)
{
echo "數(shù)據(jù)操作失敗";
}
else
{
if($this->conn->affected_rows>0)
{
return $res;
}
else
{
echo "0行數(shù)據(jù)受影響!";
}
}
}
//返回受影響數(shù)據(jù)行數(shù)
function getResultNum($sql){
$res=$this->conn->query($sql);
return mysqli_num_rows($res);
}
//關(guān)閉數(shù)據(jù)庫
public function close()
{
@mysqli_close($this->conn);
}
}
?>
然后就可以調(diào)用了
index.php
<?php
require_once "mysql.php";
$conn=new Mysql();
$sql="select * from user";
//執(zhí)行查詢并獲取查詢結(jié)果
$result=$conn->sql($sql);
//輸出受影響數(shù)據(jù)行數(shù)
$num=$conn->getResultNum($sql);
echo "影響的行數(shù):".$num;
//讀取并輸出記錄
while ($row = mysqli_fetch_assoc($result))
{
echo "{$row['name']} ";
echo "{$row['password']}";
}
//關(guān)閉數(shù)據(jù)庫
$conn->close();
更多關(guān)于PHP相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《php+mysqli數(shù)據(jù)庫程序設(shè)計技巧總結(jié)》、《php面向?qū)ο蟪绦蛟O(shè)計入門教程》、《PHP數(shù)組(Array)操作技巧大全》、《PHP基本語法入門教程》、《php字符串(string)用法總結(jié)》、《php+mysql數(shù)據(jù)庫操作入門教程》及《php常見數(shù)據(jù)庫操作技巧匯總》
希望本文所述對大家PHP程序設(shè)計有所幫助。
相關(guān)文章
php使用變量動態(tài)創(chuàng)建類的對象用法示例
這篇文章主要介紹了php使用變量動態(tài)創(chuàng)建類的對象,涉及php面向?qū)ο蟪绦蛟O(shè)計中對象的動態(tài)創(chuàng)建相關(guān)操作技巧,需要的朋友可以參考下2017-02-02
PHP 使用openssl 擴展實現(xiàn)公鑰加密的方法
下面小編就為大家分享一篇PHP 使用openssl 擴展實現(xiàn)公鑰加密的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-03-03
不支持fsockopen但支持culr環(huán)境下下ucenter與modoer通訊問題
網(wǎng)站上線,modoer與ucenter 下不能通訊折騰了我差不多二天,開始都以為自己的配置出問題,移植了平臺后就不能通訊了,修改了幾次配置,都沒有成功2011-08-08

