問題描述
我目前正在使用 MySQLi,試圖弄清楚它是如何工作的.在我目前的項目中,我總是喜歡在編碼時回顯查詢字符串,以確保一切正確,并快速調試我的代碼.但是……我如何使用準備好的 MySQLi 語句來做到這一點?
I'm playing around with MySQLi at the moment, trying to figure out how it all works. In my current projects I always like to echo out a query string while coding, just to make sure that everything is correct, and to quickly debug my code. But... how can I do this with a prepared MySQLi statement?
示例:
$id = 1;
$baz = 'something';
if ($stmt = $mysqli->prepare("SELECT foo FROM bar WHERE id=? AND baz=?")) {
$stmt->bind_param('is',$id,$baz);
// how to preview this prepared query before acutally executing it?
// $stmt->execute();
}
我一直在瀏覽這個列表(http://www.php.net/mysqli) 但沒有任何運氣.
I've been going through this list (http://www.php.net/mysqli) but without any luck.
編輯
好吧,如果在 MySQLi 中不可能,也許我會堅持這樣的:
Well, if it's not possible from within MySQLi, maybe I'll stick with something like this:
function preparedQuery($sql,$params) {
for ($i=0; $i<count($params); $i++) {
$sql = preg_replace('/?/',$params[$i],$sql,1);
}
return $sql;
}
$id = 1;
$baz = 'something';
$sql = "SELECT foo FROM bar WHERE id=? AND baz=?";
echo preparedQuery($sql,array($id,$baz));
// outputs: SELECT foo FROM bar WHERE id=1 AND baz=something
顯然遠非完美,因為它仍然相當多余—我想阻止的事情—它也沒有讓我知道 MySQLi 對數據做了什么.但是我想通過這種方式我可以快速查看所有數據是否都存在并且位于正確的位置,并且與手動將變量擬合到查詢中相比,它可以為我節省一些時間—對于許多變量,這可能會很痛苦.
Far from perfect obviously, since it's still pretty redundant — something I wanted to prevent — and it also doesn't give me an idea as to what's being done with the data by MySQLi. But I guess this way I can quickly see if all the data is present and in the right place, and it'll save me some time compared to fitting in the variables manually into the query — that can be a pain with many vars.
推薦答案
我認為你不能——至少不是你希望的那樣.您要么必須自己構建查詢字符串并執行它(即不使用語句),要么尋找或創建支持該功能的包裝器.我使用的是 Zend_Db,這就是我要做的:
I don't think you can - at least not in the way that you were hoping for. You would either have to build the query string yourself and execute it (ie without using a statement), or seek out or create a wrapper that supports that functionality. The one I use is Zend_Db, and this is how I would do it:
$id = 5;
$baz = 'shazam';
$select = $db->select()->from('bar','foo')
->where('id = ?', $id)
->where('baz = ?', $baz); // Zend_Db_Select will properly quote stuff for you
print_r($select->__toString()); // prints SELECT `bar`.`foo` FROM `bar` WHERE (id = 5) AND (baz = 'shazam')
這篇關于如何回顯 MySQLi 準備好的語句?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!