1:DBHelper.class.php
<?
php
class
DBHelper{
private
$mysqli
;
private
static
$host
='127.0.0.1'
;
private
static
$user
='root'
;
private
static
$pwd
='mysql'
;
private
static
$dbname
='test'
;
//
通過構造方法進行初始化操作
public
function
__construct(){
$this
->mysqli=
new
mysqli(self::
$host
,self::
$user
,self::
$pwd
,self::
$dbname
)
or
die
('數據庫鏈接出錯:'.
$this
->mysqli->
connect_error);
//
設置數據庫編碼為utf8
$this
->mysqli->query('set names utf8'
);
}
//
執行查詢語句
public
function
execute_dml(
$sql
){
$arr
=
array
();
$result
=
$this
->mysqli->query(
$sql
) or
die
(
$this
->mysqli->
error);
if
(
$result
){
while
(
$row
=
$result
->
fetch_assoc()){
//
將查詢結果封裝到一個數組中,返回給方法調用處
$arr
[]=
$row
;
}
//
釋放查詢結果資源
$result
->
free();
}
return
$arr
;
}
//
執行增加、刪除、更新語句
public
function
execute_dql(
$sql
){
$result
=
$this
->mysqli->query(
$sql
) or
die
(
$this
->mysqli->
error);
if
(!
$result
){
return
0;
//
表示操作失敗
}
else
{
if
(
$this
->mysqli->affected_rows>0
){
return
1;
//
操作成功
}
else
{
return
2;
//
沒有受影響的行
}
}
}
}
?>
?2:使用案例index.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<?
php
require_once
('DBHelper.class.php'
);
$dbhelper
=
new
DBHelper();
$sql
='select id,name,age from user'
;
$users
=
$dbhelper
->execute_dml(
$sql
);
if
(!
empty
(
$users
)){
?>
<table style="width:80%;">
<tr>
<th>ID</th>
<th>Name</th>
<th>Age</th>
<th>操作</th>
</tr>
<?
php
foreach
(
$users
as
$user
){
?>
<tr align='center'>
<td><?php
echo
$user
['id'];?></td>
<td><?php
echo
$user
['name'];?></td>
<td><?php
echo
$user
['age'];?></td>
<td>
<a href="delete.php?id=<?php echo
$user
['id'];?>">Delete</a> |&
nbsp;
<a href="show.php?id=<?php echo
$user
['id'];?>">Show</a>
</td>
</tr>
<?php }?>
</table>
<?
php
}
else
{
echo
'<h1>No result!</h1>'
;
}
?>
<hr/>
<a href="add.php" style="font-size:24px;font-weight:bold;">Add a
new
user</a>
</body>
</html>
?
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061
微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元

