php pdo mysql存储过程_MySQL从PHP PDO中的存储过程检索变量
事實證明,這是一個已經持續了很長時間的錯誤…自2005年以來!
有多種方法可以獲得答案,我找到了其中一個并證明了這一點……
‘技巧’是從’MysqL’程序獲取輸出.這是一個“兩個階段”的過程.
>第一部分是使用您的輸入運行過程,并告訴它存儲結果的MysqL變量.
>然后,運行單獨的查詢以“選擇”那些“MysqL”變量.
更新(2017年1月):
這是一個示例,顯示了’IN’,’INOUT’和’OUT’MysqL過程參數的變量的使用.
在我們開始之前,有一些提示:
>開發時:在“模擬模式”下運行PDO,因為它在確定過程調用中的錯誤時更可靠.
>僅將PHP變量綁定到過程’IN’參數.
當您嘗試將變量綁定到INOUT和OUT參數時,您將獲得一些非常奇怪的運行時錯誤.
像往常一樣,我傾向于提供比所需更多的評論; – /
運行時環境(XAMPP):
> PHP:5.4.4
> MysqL:5.5.16
源代碼:
CREATE PROCEDURE `demoSpInOutsqlVars`(IN pInput_Param INT,/* PHP Variable will bind to this*/
/* --- */
INOUT pInOut_Param INT,/* contains name of the sql User variable that will be read and set by MysqL */
OUT pOut_Param INT) /* contains name of the sql User variable that will be set by MysqL */
BEGIN
/*
* Pass the full names of sql User Variable for these parameters. e.g. '@varInOutParam'
* These 'sql user variables names' are the variables that MysqL will use for:
* 1) finding values
* 2) storing results
*
* It is similar to 'variable variables' in PHP.
*/
SET pInOut_Param := ABS(pInput_Param) + ABS(pInOut_Param); /* always positive sum */
SET pOut_Param := ABS(pInput_Param) * -3; /* always negative * 3 */
END$$
數據庫連接:
$db = appDIC('getDbConnection','default'); // get the default db connection
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES,true);
$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE,PDO::FETCH_ASSOC);
注意:輸出與EMULATE_PREPARES = false相同.
設置將使用的所有PHP變量:
$PHPInParam = 5;
$PHPInOutParam = 404; /* PHP InOut variable ==> read and should be changed */
$PHPOutParam = null; /* PHP Out variable ==> should be changed */
定義并準備sql過程調用:
$sql = "call demoSpInOut(:PHPInParam,@varInOutParam,/* MysqL variable name will be read and updated */
@varOutParam)"; /* MysqL variable name that will be written to */
$stmt = $db->prepare($sql);
綁定PHP變量并設置sql變量:
> 1)綁定PHP變量
$stmt-> bindParam(‘:PHPInParam’,$PHPInParam,PDO :: PARAM_INT);
> 2)設置sql用戶INOUT變量
$db-> exec(“SET @varInOutParam = $PHPInOutParam”); //這是安全的,因為它只是將值設置為MysqL變量.
執行程序:
$allOk = $stmt->execute();
將sql變量放入PHP變量中:
$sql = "SELECT @varInOutParam AS PHPInOutParam,@varOutParam AS PHPOutParam
FROM dual";
$results = current($db->query($sql)->fetchAll());
$PHPInOutParam = $results['PHPInOutParam'];
$PHPOutParam = $results['PHPOutParam'];
注意:也許不是最好的方法; – /
"$PHPInParam:" => "5"
"$PHPInOutParam:" => "409"
"$PHPOutParam:" => "-15"
總結
以上是生活随笔為你收集整理的php pdo mysql存储过程_MySQL从PHP PDO中的存储过程检索变量的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: mysql router测试_MySQL
- 下一篇: django mysql debug_部