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' ; // 通過(guò)構(gòu)造方法進(jìn)行初始化操作 public function __construct(){ $this ->mysqli= new mysqli(self:: $host ,self:: $user ,self:: $pwd ,self:: $dbname ) or die ('數(shù)據(jù)庫(kù)鏈接出錯(cuò):'. $this ->mysqli-> connect_error); // 設(shè)置數(shù)據(jù)庫(kù)編碼為utf8 $this ->mysqli->query('set names utf8' ); } // 執(zhí)行查詢語(yǔ)句 public function execute_dml( $sql ){ $arr = array (); $result = $this ->mysqli->query( $sql ) or die ( $this ->mysqli-> error); if ( $result ){ while ( $row = $result -> fetch_assoc()){ // 將查詢結(jié)果封裝到一個(gè)數(shù)組中,返回給方法調(diào)用處 $arr []= $row ; } // 釋放查詢結(jié)果資源 $result -> free(); } return $arr ; } // 執(zhí)行增加、刪除、更新語(yǔ)句 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; // 沒(méi)有受影響的行 } } } } ?>
?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>
?
更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號(hào)聯(lián)系: 360901061
您的支持是博主寫(xiě)作最大的動(dòng)力,如果您喜歡我的文章,感覺(jué)我的文章對(duì)您有幫助,請(qǐng)用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點(diǎn)擊下面給點(diǎn)支持吧,站長(zhǎng)非常感激您!手機(jī)微信長(zhǎng)按不能支付解決辦法:請(qǐng)將微信支付二維碼保存到相冊(cè),切換到微信,然后點(diǎn)擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對(duì)您有幫助就好】元
