php面向?qū)ο筮B接數(shù)據(jù)庫實現(xiàn)增刪改的方法:首先創(chuàng)建Mysql類并定義變量;然后通過構(gòu)造函數(shù)初始化類;接著連接數(shù)據(jù)庫,并自定義插入數(shù)據(jù)方法;最后使用update和delete方法修改或刪除數(shù)據(jù)即可。
推薦:《PHP視頻教程》
PHP(面向?qū)ο?連接數(shù)據(jù)庫,實現(xiàn)基本的增刪改查
1、創(chuàng)建mysql_class.php文件然后在該文件中創(chuàng)建Mysql類,并定義變量
<?php class Mysql{ private $host;//服務(wù)器地址 private $root;//用戶名 private $password;//密碼 private $database;//數(shù)據(jù)庫名 //后面所提到的各個方法都放在這個類里 //... } ?>
2、通過構(gòu)造函數(shù)初始化類
function __construct($host,$root,$password,$database){ $this->host = $host; $this->root = $root; $this->password = $password; $this->database = $database; $this->connect(); }
對于connect()方法,下一步再說
3、創(chuàng)建連接數(shù)據(jù)庫及關(guān)閉數(shù)據(jù)庫方法
function connect(){ $this->conn = mysql_connect($this->host,$this->root,$this->password) or die("DB Connnection Error !".mysql_error()); mysql_select_db($this->database,$this->conn); mysql_query("set names utf8"); } function dbClose(){ mysql_close($this->conn); }
4、對mysql_query()、mysql_fetch_array()、mysql_num_rows()函數(shù)進(jìn)行封裝
function query($sql){ return mysql_query($sql); } function myArray($result){ return mysql_fetch_array($result); } function rows($result){ return mysql_num_rows($result); }
5、自定義查詢數(shù)據(jù)方法
function select($tableName,$condition){ return $this->query("SELECT * FROM $tableName $condition"); }
6、自定義插入數(shù)據(jù)方法
function insert($tableName,$fields,$value){ $this->query("INSERT INTO $tableName $fields VALUES$value"); }
7、自定義修改數(shù)據(jù)方法
function update($tableName,$change,$condition){ $this->query("UPDATE $tableName SET $change $condition"); }
8、自定義刪除數(shù)據(jù)方法
function delete($tableName,$condition){ $this->query("DELETE FROM $tableName $condition"); }
現(xiàn)在,數(shù)據(jù)庫操作類已經(jīng)封裝好了,下面我們就來看看該怎么使用。
我們用的還是在PHP連接數(shù)據(jù)庫,實現(xiàn)最基本的增刪改查(面向過程)一文中所涉及到的數(shù)據(jù)庫及表(表中數(shù)據(jù)自己添加):
9、那么我們先對數(shù)據(jù)庫操作類進(jìn)行實例化
$db = new Mysql("localhost","root","admin","beyondweb_test");
實例化可以在mysql_class.php文件中的Mysql類之外進(jìn)行。
然后我們再創(chuàng)建一個test.php文件,首先把mysql_class.php文件引入
<?php require("mysql_class.php"); ?>
然后我們就開始操作吧
10、向表中插入數(shù)據(jù)
<?php $insert = $db->insert("user","(nikename,email)","(#beyondweb#,#beyondwebcn@xx.com#)");//請把#號替換為單引號 $db->dbClose(); ?>
11、修改表中數(shù)據(jù)
<?php $update = $db->update("user","nikename = #beyondwebcn#","where id = #2#");//請把#號替換為單引號 $db->dbClose(); ?>
12、查詢表中數(shù)據(jù)并輸出
<?php $select = $db->select("user"); $row = $db->rows($select); if($row>=1){ ?> <table border="1px"> <tr> <th>id</th> <th>nikename</th> <th>email</th> </tr> <?php while($array = $db->myArray($select)){ echo "<tr>"; echo "<td>".$array[#id#]."</td>";//請把#號替換為單引號 echo "<td>".$array[#nikename#]."</td>";//請把#號替換為單引號 echo "<td>".$array[#email#]."</td>";//請把#號替換為單引號 echo "</tr>"; } ?> </table> <?php }else{ echo "查不到任何數(shù)據(jù)!"; } $db->dbClose(); ?>
13、刪除表中數(shù)據(jù)
<?php $delete = $db->delete("user","where nikename = #beyondweb#");//請把#號替換為單引號 $db->dbClose(); ?>