php pdo mysql存储过程_MySQL从PHP PDO中的存储过程检索变量
事實(shí)證明,這是一個(gè)已經(jīng)持續(xù)了很長時(shí)間的錯(cuò)誤…自2005年以來!
有多種方法可以獲得答案,我找到了其中一個(gè)并證明了這一點(diǎn)……
‘技巧’是從’MysqL’程序獲取輸出.這是一個(gè)“兩個(gè)階段”的過程.
>第一部分是使用您的輸入運(yùn)行過程,并告訴它存儲(chǔ)結(jié)果的MysqL變量.
>然后,運(yùn)行單獨(dú)的查詢以“選擇”那些“MysqL”變量.
更新(2017年1月):
這是一個(gè)示例,顯示了’IN’,’INOUT’和’OUT’MysqL過程參數(shù)的變量的使用.
在我們開始之前,有一些提示:
>開發(fā)時(shí):在“模擬模式”下運(yùn)行PDO,因?yàn)樗诖_定過程調(diào)用中的錯(cuò)誤時(shí)更可靠.
>僅將PHP變量綁定到過程’IN’參數(shù).
當(dāng)您嘗試將變量綁定到INOUT和OUT參數(shù)時(shí),您將獲得一些非常奇怪的運(yùn)行時(shí)錯(cuò)誤.
像往常一樣,我傾向于提供比所需更多的評(píng)論; – /
運(yùn)行時(shí)環(huán)境(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$$
數(shù)據(jù)庫連接:
$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相同.
設(shè)置將使用的所有PHP變量:
$PHPInParam = 5;
$PHPInOutParam = 404; /* PHP InOut variable ==> read and should be changed */
$PHPOutParam = null; /* PHP Out variable ==> should be changed */
定義并準(zhǔn)備sql過程調(diào)用:
$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變量并設(shè)置sql變量:
> 1)綁定PHP變量
$stmt-> bindParam(‘:PHPInParam’,$PHPInParam,PDO :: PARAM_INT);
> 2)設(shè)置sql用戶INOUT變量
$db-> exec(“SET @varInOutParam = $PHPInOutParam”); //這是安全的,因?yàn)樗皇菍⒅翟O(shè)置為MysqL變量.
執(zhí)行程序:
$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"
總結(jié)
以上是生活随笔為你收集整理的php pdo mysql存储过程_MySQL从PHP PDO中的存储过程检索变量的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: mysql router测试_MySQL
- 下一篇: django mysql debug_部