Codeigniter架構使用Mysql預存程序的例子

來源:互聯網
上載者:User

執行預存程序

$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();

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.