萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 呼叫 MySQL 預存程序四大模式完整範例

前置準備

範例使用舊版 mysql_* 函式 (已棄用),現代專案請改用 mysqli 或 PDO。核心概念相同:透過使用者變數 @var 接收 OUT/INOUT 參數。

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

<?php
$returnValue = '';
try {
    mysql_query("SET @Return = ''");
    $spname = 'P__Test_GetInfo1';
    // 呼叫:@Return 為 OUT 參數,$userId、$pwd 為 IN 參數
    mysql_query("CALL $spname(@Return, '{$userId}', '{$pwd}')") 
        or die("[$spname] Query failed: " . mysql_error());
    
    // 取得 OUT 參數值
    $result = mysql_query("SELECT @Return");
    $row = mysql_fetch_row($result);
    $returnValue = $row[0];
} catch (Exception $e) {
    echo $e;
}
echo $returnValue;
?>

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

<?php
$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";
?>

模式三:回傳單一結果集

<?php
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 的 next_result() 與 store_result()。

<?php
$rows = [];
$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()) {
                $rows[] = $row;
            }
            $result->close();
        }
    } while ($db->next_result());
}
$db->close();
print_r($rows);
/*
對應預存程序結構:
...
SELECT * FROM T1 WHERE ...;
SELECT * FROM T2 WHERE ...;
...
*/
?>

最佳實踐建議

  • 全面遷移至 mysqli 或 PDO,支援預處理語句防止 SQL 注入。
  • 使用 CALL proc(@out1, @out2, ?) 搭配 bind_param 綁定參數。
  • 預存程序中使用 SELECT @out_param 回傳輸出值,或直接在 PHP 中 SELECT @out_param 查詢。
copyright © 萬盛學電腦網 all rights reserved