本文實(shí)例講述了PHP封裝mysqli基于面向?qū)ο蟮膍ysql數(shù)據(jù)庫(kù)操作與用法。分享給大家供大家參考,具體如下:
首先封裝好mysql類(lèi)
mysql.php
?php
class Mysql{
private static $host="localhost";
private static $user="root";
private static $password="123456";
private static $dbName="test"; //數(shù)據(jù)庫(kù)名
private static $charset="utf8"; //字符編碼
private static $port="3306"; //端口號(hào)
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ù)庫(kù)連接失敗!".$this->conn->connect_error);
}else{
echo "連接成功!";
}
$this->conn->query("set names ".self::$charset);
}
//執(zhí)行sql語(yǔ)句
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ù)庫(kù)
public function close()
{
@mysqli_close($this->conn);
}
}
?>
然后就可以調(diào)用了
index.php
?php
require_once "mysql.php";
$conn=new Mysql();
$sql="select * from user";
//執(zhí)行查詢(xún)并獲取查詢(xún)結(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ù)庫(kù)
$conn->close();
更多關(guān)于PHP相關(guān)內(nèi)容感興趣的讀者可查看本站專(zhuān)題:《php+mysqli數(shù)據(jù)庫(kù)程序設(shè)計(jì)技巧總結(jié)》、《php面向?qū)ο蟪绦蛟O(shè)計(jì)入門(mén)教程》、《PHP數(shù)組(Array)操作技巧大全》、《PHP基本語(yǔ)法入門(mén)教程》、《php字符串(string)用法總結(jié)》、《php+mysql數(shù)據(jù)庫(kù)操作入門(mén)教程》及《php常見(jiàn)數(shù)據(jù)庫(kù)操作技巧匯總》
希望本文所述對(duì)大家PHP程序設(shè)計(jì)有所幫助。
您可能感興趣的文章:- 解決php用mysql方式連接數(shù)據(jù)庫(kù)出現(xiàn)Deprecated報(bào)錯(cuò)問(wèn)題
- php連接mysql數(shù)據(jù)庫(kù)最簡(jiǎn)單的實(shí)現(xiàn)方法
- PHP使用PDO創(chuàng)建MySQL數(shù)據(jù)庫(kù)、表及插入多條數(shù)據(jù)操作示例
- 完美解決phpstudy安裝后mysql無(wú)法啟動(dòng)(無(wú)需刪除原數(shù)據(jù)庫(kù),無(wú)需更改任何配置,無(wú)需更改端口)直接共存
- ThinkPHP框架實(shí)現(xiàn)的MySQL數(shù)據(jù)庫(kù)備份功能示例
- PHP基于pdo的數(shù)據(jù)庫(kù)操作類(lèi)【可支持mysql、sqlserver及oracle】
- PHP連接MySQL數(shù)據(jù)庫(kù)并以json格式輸出
- PHP連接MYSQL數(shù)據(jù)庫(kù)的3種常用方法
- PHP連接MySQL數(shù)據(jù)庫(kù)操作代碼實(shí)例解析