首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 相關知識

PHP 呼叫 MySQL 預存程序的四種常見模式總整理

     編輯:PHP 相關知識

MySQL 預存程序能將複雜的商業邏輯封裝在資料庫層,PHP 透過不同方式呼叫可應對各種參數與回傳需求。本文整理四種實用呼叫模式。

模式一:單一輸入/輸出參數

使用用戶變數 @Return 接收輸出值:

$returnValue = '';
try {
    mysql_query("set @Return");
    $spname = 'P__Test_GetInfo1';
    mysql_query("call $spname(@Return, '{$userId}', '{$pwd}')") 
        or die("[$spname]Query failed:" . mysql_error());
    $result_return = mysql_query("select @Return");
    $row_return = mysql_fetch_row($result_return);
    $returnValue = $row_return[0];
} catch (Exception $e) {
    echo $e;
}
echo $returnValue;

模式二:多重輸入/輸出參數

宣告多個用戶變數分別接收:

$userId = 0;
try {
    mysql_query("set @Message");
    mysql_query("set @Id");
    mysql_query("call P__Test_Login(@Message, @Id, '{$userId}', '{$pwd}')", $conn)
        or die("Query failed:".mysql_error());
    $result_mess = mysql_query("select @Message");
    $result_uid = mysql_query("select @Id");
    $row_mess = mysql_fetch_row($result_mess);
    $row_uid = mysql_fetch_row($result_uid);
    $Proc_Error = $row_mess[0];
    $uId = $row_uid[0];
} catch (Exception $e) {
    echo $e;
}
echo 'proc return message:' . $Proc_Error . '<br/>';
echo 'User id:' . $uId;

模式三:回傳單一結果集

直接遍歷查詢結果:

try {
    $spname = 'P__Test_GetData';
    $query = mysql_query("call $spname()", $conn)
        or die("[$spname]Query failed:".mysql_error());
    while ($row = mysql_fetch_array($query)) {
        echo $row['ProvinceID'] . '::' . $row['ProvinceName'];
    }
} catch (Exception $e) {
    echo $e;
}

模式四:回傳多個結果集 (需使用 mysqli)

舊版 mysql 擴充套件不支援多結果集,必須改用 mysqli:

$rows = array();
$db = new mysqli($server, $user, $psd, $dbname);
if (mysqli_connect_errno()) {
    die('Can not connect to MySQL server');
}
$db->query("SET NAMES UTF8");
$db->query("SET @Message");
if ($db->real_query("call P__Test_GetData2(@Message)")) {
    do {
        if ($result = $db->store_result()) {
            while ($row = $result->fetch_assoc()) {
                array_push($rows, $row);
            }
            $result->close();
        }
    } while ($db->next_result());
}
$db->close();
print_r($rows);

重要提醒

  • mysql_* 函式已棄用,新專案請使用 mysqli 或 PDO
  • 預存程序中的 SQL 注入風險同樣需防範
  • 多結果集處理時記得釋放每個 result 物件
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved