一、簡介
前面講解的功能開發都是簡單的調用API 完成的,沒有對資料庫進行操作。在接下來的進階功能開發中,需要使用到資料庫,所以在這一篇中,將對MySQL 資料庫的操作做一下簡單的介紹,以供讀者參考。
二、思路分析
百度開發人員中心提供了強大的雲資料庫(包括MySQL, MongoDB, Redis),在這一節教程中,我們將對大家比較熟悉的MySQL 資料庫進行操作示範,實現微信與資料庫的互動。
在BAE應用中使用雲資料庫十分簡單,資料庫列表中的名稱即是串連資料庫時的dbname。使用者名稱、密碼、串連地址和連接埠在應用中通過環境變數取出。
可使用標準的PHP Mysql 或PHP Mysqli 擴充訪問資料庫,BAE的PHP中已提供這兩個擴充,應用可直接使用。
三、建立BAE MySQL資料庫
3.1 登陸百度開發人員中心 -> 管理中心 -> 選擇應用 -> 雲環境 -> 服務管理 -> MySQL(雲資料庫) -> 建立資料庫
3.2 建立資料庫
注意:每個應用有且只有一個資料庫享受1G免費配額,其餘資料庫均不享受免費配額優惠。只有將已使用免費配額的資料庫刪除,才能再次使用此項優惠。
3.3 建立成功
在這裡可以看到資料庫的名稱,也就是dbname,後面會使用到。
點擊 “phpMyadmin” 訪問資料庫。
3.4 phpMyadmin介面
建立資料表,輸入表名及欄位數,點擊 “執行” 建立表。
3.5 建立表
輸入欄位名及欄位類型,輸入完畢後,點擊下面的“儲存”,完成表的建立。
3.6 建立完成
修改id 欄位為主鍵並添加AUTO_INCREMENT;修改from_user 欄位為唯一(UNIQUE),完成表的修改。
建表操作也可以使用以下SQL陳述式完成:
CREATE TABLE IF NOT EXISTS `test_mysql` ( `id` int(11) NOT NULL AUTO_INCREMENT, `from_user` varchar(40) DEFAULT NULL, `account` varchar(40) DEFAULT NULL, `password` varchar(40) DEFAULT NULL, `update_time` datetime DEFAULT NULL, PRIMARY KEY (`id`), UNIQUE KEY `from_user` (`from_user`));
phpMyAdmin 操作
資料庫及資料表的建立到此結束,下面將編寫代碼對資料庫及資料表的使用做詳細講解。
四、官方樣本(PHP MySQL)
BAE 官方提供的demo(PHP MySQL)樣本如下:
mysql/basic.php 檔案內容
<!--?php/** * MySQL樣本,通過該樣本可熟悉BAE平台MySQL的使用(CRUD) */require_once("../configure.php"); /*替換為你自己的資料庫名(可從管理中心查看到)*/ $dbname = MYSQLNAME; /*從環境變數裡取出資料庫連接需要的參數*/ $host = getenv('HTTP_BAE_ENV_ADDR_SQL_IP'); $port = getenv('HTTP_BAE_ENV_ADDR_SQL_PORT'); $user = getenv('HTTP_BAE_ENV_AK'); $pwd = getenv('HTTP_BAE_ENV_SK'); /*接著調用mysql_connect()串連伺服器*/ $link = @mysql_connect("{$host}:{$port}",$user,$pwd,true); if(!$link) { die("Connect Server Failed: " . mysql_error()); } /*串連成功後立即調用mysql_select_db()選中需要串連的資料庫*/ if(!mysql_select_db($dbname,$link)) { die("Select Database Failed: " . mysql_error($link)); } /*至此串連已完全建立,就可對當前資料庫進行相應的操作了*/ /*!!!注意,無法再通過本次串連調用mysql_select_db來切換到其它資料庫了!!!*/ /* 需要再串連其它資料庫,請再使用mysql_connect+mysql_select_db啟動另一個串連*/ /** * 接下來就可以使用其它標準php mysql函數操作進行資料庫操作 */ //建立一個資料庫表 $sql = "create table if not exists test_mysql( id int primary key auto_increment, no int, name varchar(1024), key idx_no(no))"; $ret = mysql_query($sql, $link); if ($ret === false) { die("Create Table Failed: " . mysql_error($link)); } else { echo "Create Table Succeed<br /-->"; } //插入資料 $sql = "insert into test_mysql(no, name) values(2007,'this is a test message'), (2008,'this is another test message'), (2009,'xxxxxxxxxxxxxx')"; $ret = mysql_query($sql, $link); if ($ret === false) { die("Insert Failed: " . mysql_error($link)); } else { echo "Insert Succeed"; } //刪除資料 $sql = "delete from test_mysql where no = 2008"; $ret = mysql_query($sql, $link); if ($ret === false) { die("Delete Failed: " . mysql_error($link)); } else { echo "Delete Succeed"; } //修改資料 $sql = "update test_mysql set name = 'yyyyyy' where no = 2009"; $ret = mysql_query($sql, $link); if ($ret === false) { die("Update Failed: " . mysql_error($link)); } else { echo "Update Succeed"; } //檢索資料 $sql = "select id,no,name from test_mysql"; $ret = mysql_query($sql, $link); if ($ret === false) { die("Select Failed: " . mysql_error($link)); } else { echo "Select Succeed"; while ($row = mysql_fetch_assoc($ret)) { echo "{$row['id']} {$row['no']} {$row['name']}"; } } //刪除表 $sql = "drop table if exists test_mysql"; $ret = mysql_query($sql, $link); if ($ret === false) { die("Drop Table Failed: " . mysql_error($link)); } else { echo "Drop Table Succeed"; } ?>
configure.php 檔案內容
<!--?php /***設定資料庫名稱***/ define("MYSQLNAME", "qzMlSkByflhScPCOFtax"); ?-->
測試使用:
執行成功。
五、修改成可調用的函數形式(PHP MySQL)
5.1 建立資料表
//建立一個資料庫表function _create_table($sql){ mysql_query($sql) or die('建立表失敗,錯誤資訊:'.mysql_error()); return "建立表成功";}
5.2 插入資料
//插入資料function _insert_data($sql){ if(!mysql_query($sql)){ return 0; //插入資料失敗 }else{ if(mysql_affected_rows()>0){ return 1; //插入成功 }else{ return 2; //沒有行受到影響 } }}
5.3 刪除資料
//刪除資料function _delete_data($sql){ if(!mysql_query($sql)){ return 0; //刪除失敗 }else{ if(mysql_affected_rows()>0){ return 1; //刪除成功 }else{ return 2; //沒有行受到影響 } }}
5.4 修改資料
//修改資料function _update_data($sql){ if(!mysql_query($sql)){ return 0; //更新資料失敗 }else{ if(mysql_affected_rows()>0){ return 1; //更新成功; }else{ return 2; //沒有行受到影響 } }}
5.5 檢索資料
//檢索資料function _select_data($sql){ $ret = mysql_query($sql) or die('SQL語句有錯誤,錯誤資訊:'.mysql_error()); return $ret;}
5.6 刪除資料表
//刪除表function _drop_table($sql){ mysql_query($sql) or die('刪除表失敗,錯誤資訊:'.mysql_error()); return "刪除表成功";}
將以上函數和串連資料庫的代碼結合起來,產生mysql_bae.func.php 檔案,供下面測試使用。
六、測試MySQL 函數使用
6.1 建立檔案dev_mysql.php 在同一目錄下並引入mysql_bae.func.php 檔案
require_once './mysql_bae.func.php';
6.2 測試建立表
將上面使用phpMyAdmin 建立的test_mysql 表刪除,測試語句如下:
//建立表$create_sql = "CREATE TABLE IF NOT EXISTS `test_mysql` ( `id` int(11) NOT NULL AUTO_INCREMENT, `from_user` varchar(40) DEFAULT NULL, `account` varchar(40) DEFAULT NULL, `password` varchar(40) DEFAULT NULL, `update_time` datetime DEFAULT NULL, PRIMARY KEY (`id`), UNIQUE KEY `from_user` (`from_user`))"; echo _create_table($create_sql);
測試正確結果:
到phpMyAdmin中查看
故意將SQL語句寫錯
測試錯誤結果:
6.3 測試插入資料
測試語句如下:
//插入資料$insert_sql = "insert into test_mysql(from_user, account, password, update_time) values('David','860510', 'abcabc', '2013-09-29 17:14:28')"; $res = _insert_data($insert_sql);if($res == 1){ echo "插入成功";}else{ echo "插入失敗";}
測試結果:
6.4 測試更新資料
測試語句如下:
//更新資料$update_sql = "update test_mysql set account = 860512 where account = 860510"; $res = _update_data($update_sql);if($res == 1){ echo "更新成功";}elseif($res == 0){ echo "更新失敗";}elseif($res == 2){ echo "沒有行受到影響";}
測試結果:
再次更新:
6.5 測試刪除資料
測試語句如下:
//刪除資料$delete_sql = "delete from test_mysql where account = 860512"; $res = _delete_data($delete_sql);if($res == 1){ echo "刪除成功";}elseif($res == 0){ echo "刪除失敗";}elseif($res == 2){ echo "沒有該條記錄";}
測試結果:
再次刪除:
6.6 測試檢索資料
再次執行上面的插入操作做檢索測試,測試語句如下:
//檢索資料$select_sql = "select * from test_mysql"; $result = _select_data($select_sql); while($rows = mysql_fetch_array($result,MYSQL_ASSOC)){ echo $rows[id]."--".$rows[from_user]."--".$rows[account]."--".$rows[password]."--".$rows[update_time]; echo ""; }
測試結果:
6.7 測試刪除表
測試語句如下:
//刪除表$drop_sql = "drop table if exists test_mysql";
echo _drop_table($drop_sql);
測試結果:
MySQL 函數測試全部成功。
七、實現與微信的互動(Mysql 擴充)
保證資料庫中存在test_msyql表,這裡測試微信對MySQL資料庫的增刪改查操作,不考慮特殊情況,只按照下面的方法測試:
1. 綁定+賬戶+密碼如:綁定+860512+abc123 2. 查詢如:查詢 3. 修改+舊密碼+新密碼如:修改+abc123+123456 4. 刪除如:刪除
7.1 引入mysql_bae.func.php 檔案
//引入資料庫函數檔案
require_once 'mysql_bae.func.php';
7.2 前置操作
A. 將輸入的語句拆分成數組,以“+”號分隔
$keywords = explode("+",$keyword);
B. 擷取目前時間
//擷取目前時間$nowtime=date("Y-m-d G:i:s");
C. 判斷使用者是否已經綁定
//判斷是否已經綁定$select_sql="SELECT id from test_mysql WHERE from_user='$fromUsername'";$res=_select_data($select_sql);$rows=mysql_fetch_array($res, MYSQL_ASSOC);if($rows[id] <> ''){ $user_flag='y'; }
7.3 測試插入操作
測試代碼:
if(trim($keywords[0] == '綁定')){ if($user_flag <> 'y'){ $insert_sql="INSERT INTO test_mysql(from_user, account, password, update_time) VALUES('$fromUsername','$keywords[1]','$keywords[2]','$nowtime')"; $res = _insert_data($insert_sql); if($res == 1){ $contentStr = "綁定成功"; }elseif($res == 0){ $contentStr = "綁定失敗"; } }else{ $contentStr = "該賬戶已綁定"; }}
測試結果:
7.4 測試查詢操作
測試代碼:
if(trim($keywords[0] == '查詢')){ $select_sql="SELECT * FROM test_mysql WHERE from_user='$fromUsername'"; $select_res=_select_data($select_sql); $rows=mysql_fetch_assoc($select_res); if($rows[id] <> ''){ $contentStr="賬戶:$rows[account]\n"."密碼:$rows[password]\n"."From_user:$rows[from_user]\n"."更新時間:$rows[update_time]"; }else{ $contentStr="您還未綁定賬戶,查詢不到相關資訊,請先綁定,謝謝!"; }}
測試結果:
7.5 測試更新操作
測試代碼:
if(trim($keywords[0] == "修改")){ $old_password=$keywords[1]; $new_password=$keywords[2]; $select_password_sql="SELECT * FROM test_mysql WHERE from_user='$fromUsername'"; $select_res=_select_data($select_password_sql); $rows=mysql_fetch_assoc($select_res); if($old_password == $rows[password]){ $update_sql="UPDATE test_mysql SET password='$new_password' WHERE from_user='$fromUsername'"; $res = _update_data($update_sql); if($res == 1){ $contentStr = "修改成功"; }elseif($res == 0){ $contentStr = "修改失敗"; } }else{ $contentStr = "原密碼有誤,請確認後重試"; }}
測試結果:
7.6 測試刪除操作
測試代碼:
if(trim($keywords[0] == "刪除")){ $delete_sql="DELETE FROM test_mysql WHERE from_user='$fromUsername'"; $res = _delete_data($delete_sql); if($res == 1){ $contentStr = "刪除成功"; }elseif($res == 0){ $contentStr = "刪除失敗"; }}
測試結果:
與微信的互動測試成功。
八、PHP Mysqli 擴充,封裝成類
將Mysqli 擴充封裝成類使用,代碼如下:
<!--?php require_once 'includes/configure.php'; class MySQLi_BAE{ private $mysqli; private $host; private $user; private $password; private $port; private $database; //在類之外訪問私人變數時使用 function __get($property_name){ if(isset($this--->$property_name)){ return($this->$property_name); }else{ return(NULL); } } function __set($property_name, $value){ $this->$property_name=$value; } function __construct(){ /*從平台擷取查詢要串連的資料庫名稱*/ $this->database = MYSQLNAME; /*從環境變數裡取出資料庫連接需要的參數*/ $this->host = getenv('HTTP_BAE_ENV_ADDR_SQL_IP'); $this->user = getenv('HTTP_BAE_ENV_AK'); $this->password = getenv('HTTP_BAE_ENV_SK'); $this->port = getenv('HTTP_BAE_ENV_ADDR_SQL_PORT'); $this->mysqli = new mysqli($this->host, $this->user, $this->password, $this->database, $this->port); if($this->mysqli->connect_error){ die("Connect Server Failed:".$this->mysqli->error); } $this->mysqli->query("set names utf8"); } //dql statement function execute_dql($query){ $res = $this->mysqli->query($query) or die("操作失敗".$this->mysqli->error); return $res; //$this->mysqli->close(); } //dml statement function execute_dml($query){ $res = $this->mysqli->query($query) or die("操作失敗".$this->mysqli->error); if(!$res){ return 0;//失敗 }else{ if($this->mysqli->affected_rows > 0){ return 1;//執行成功 }else{ return 2;//沒有行受影響 } } //$this->mysqli->close(); }}?>
九、測試類別的使用
9.1 測試DML操作
測試代碼:
<!--?php require_once "MySQLi_BAE.class.php"; $mysqli_BAE=new MySQLi_BAE(); //**************dml*******************$sql="insert into test_mysql (from_user, account, password, update_time) values('David','860510', 'abcabc', '2013-09-27 17:14:28')"; //$sql="update test_mysql set account = 860512 where account = 860510"; //$sql="delete from test_mysql where account = 860512"; $res=$mysqli_BAE--->execute_dml($sql); if($res==0){ echo "執行失敗";}elseif($res==1){ echo "執行成功";}else{ echo "沒有行數影響";}?>
測試結果:
9.2 測試DQL操作
測試代碼:
<!--?php require_once "MySQLi_BAE.class.php"; $mysqli_BAE=new MySQLi_BAE(); //**************dql******************$sql="select * from test_mysql"; $res=$mysqli_BAE--->execute_dql($sql); while($row=$res->fetch_row()){ foreach($row as $key=>$val){ echo "$val--"; } echo '';} $res->free();?>
測試結果:
十、實現與微信的互動(Mysqli 擴充)
10.1 前置操作
A. 引入MySQLi_BAE.class.php 檔案
//引入資料庫函數檔案require_once "MySQLi_BAE.class.php";
B. 執行個體化對象
public function __construct(){ $this->mysqli_BAE=new MySQLi_BAE();}
10.2 測試插入操作
測試代碼:
$insert_sql="INSERT INTO test_mysql(from_user, account, password, update_time) VALUES('$fromUsername',
'$keywords[1]','$keywords[2]','$nowtime')";$res = $this->mysqli_BAE->execute_dml($insert_sql);
測試結果:
10.3 測試查詢操作
測試代碼:
$select_sql="SELECT * FROM test_mysql WHERE from_user='$fromUsername'";
$select_res=$this->mysqli_BAE->execute_dql($select_sql);$rows=$select_res->fetch_array(MYSQLI_ASSOC);
測試結果:
10.4 測試更新操作
測試代碼:
$update_sql="UPDATE test_mysql SET password='$new_password' WHERE from_user='$fromUsername'";
$res = $this->mysqli_BAE->execute_dml($update_sql);
測試結果:
10.5 測試刪除操作
測試代碼:
$delete_sql="DELETE FROM test_mysql WHERE from_user='$fromUsername'";
$res = $this->mysqli_BAE->execute_dml($delete_sql);
測試結果:
與微信互動測試成功。
十一、完整代碼擷取
請訪問 樂思樂享 官方論壇
URL:http://pan.baidu.com/s/1c0s3Jby
十二、關注
請關注 卓錦蘇州 微信公眾帳號,卓錦蘇州 基於BAE 平台開發,針對於主流的微信功能進行開發測試。
您可以關注 卓錦蘇州 公眾帳號進行功能測試,以及擷取新的應用開發。
1. 登入微信用戶端,通訊錄 -> 添加朋友 -> 尋找公眾號 -> zhuojinsz,尋找並關注。
2. 掃描二維碼:
卓錦蘇州 功能列表:
感謝閱讀,希望能協助到大家,謝謝大家對本站的支援!