執行預存程序
$query = $this -> db -> query('CALL YOU_SP_NAME');
$result = $query -> result();
這個問題不大,就像是執行普通 SQL 陳述式一樣。
使用預存程序遇到的問題
在用了預存程序之後,探索資料庫連結並不能使用 持續連結,即 需要把 database.php 裡的 $db['pconnect'] 設定為 FALSE,否則會出現連結資料庫失敗的錯誤。
另外,當執行完預存程序之後,如果再執行其它的資料庫查詢,會出現 Commands out of sync; you can't run this command now 錯誤。
查了下原因,據說是因為執行完預存程序後,沒有將結果集給釋放掉
CI 中可以通過重連資料庫的方法解決:
$this -> db -> reconnect();
如何獲得多個結果集
主要是使用 Mysqli 的 multi_query() 來獲得
關鍵代碼如下:
$mysqli = new mysqli('localhost', 'USERNAME', 'PASSWORD', 'DBNAME');
$mysqli -> query("SET NAMES utf8");
/* check connection */
if (mysqli_connect_errno()) {
printf('Connect failed: %s\n', mysqli_connect_error());
exit();
}
$query = 'CALL YOU_SP_NAME';
/* execute multi query */
if ($mysqli -> multi_query($query)) {
do {
/* store first result set */
if ($result = $mysqli -> store_result()) {
while ($row = $result -> fetch_all()) {
$all_result[] = $row;
}
$result -> free();
}
}
while ($mysqli -> next_result());
}
/* close connection */
$mysqli -> close();