問題描述
我剛剛使用 mysqli 將所有 sql 查詢更改為準(zhǔn)備好的語句.為了加快這個過程,我創(chuàng)建了一個函數(shù)(稱為 performQuery
)來代替 mysql_query
.它需要查詢、綁定(如sdss")和要傳入的變量,然后執(zhí)行所有 perpared 語句.這意味著更改我所有的舊代碼很容易.我的函數(shù)使用 mysqli get_result()
返回一個 mysqli_result
對象.
I've just changed all my sql queries to prepared statements using mysqli. To speed this process up I created a function (called performQuery
) which replaces mysql_query
. It takes the query, the bindings (like "sdss") and the variables to pass in, this then does all the perpared statement stuff. This meant changing all my old code was easy. My function returns a mysqli_result
object using mysqli get_result()
.
這意味著我可以從以下位置更改舊代碼:
This meant I could change my old code from:
$query = "SELECT x FROM y WHERE z = $var";
$result = mysql_query($query);
while ($row = mysql_fetch_assoc($result)){
echo $row['x'];
}
到
$query = "SELECT x FROM y WHERE z = ?";
$result = performQuery($query,"s",$var);
while ($row = mysql_fetch_assoc($result)){
echo $row['x'];
}
這在本地主機(jī)上運(yùn)行良好,但我的網(wǎng)絡(luò)托管服務(wù)器沒有可用的 mysqlnd,因此 get_result()
不起作用.安裝 mysqlnd 不是一個選項(xiàng).
This works fine on localhost, but my web hosting server does not have mysqlnd available, therefore get_result()
does not work. Installing mysqlnd is not an option.
從這里出發(fā)的最佳方式是什么?我可以創(chuàng)建一個替換 get_result()
的函數(shù)嗎?
What is the best way to go from here? Can I create a function which replaces get_result()
, and how?
推薦答案
這里有一個更簡潔的解決方案,基于與 lx 答案:
Here is a neater solution based on the same principle as lx answer:
function get_result( $Statement ) {
$RESULT = array();
$Statement->store_result();
for ( $i = 0; $i < $Statement->num_rows; $i++ ) {
$Metadata = $Statement->result_metadata();
$PARAMS = array();
while ( $Field = $Metadata->fetch_field() ) {
$PARAMS[] = &$RESULT[ $i ][ $Field->name ];
}
call_user_func_array( array( $Statement, 'bind_result' ), $PARAMS );
$Statement->fetch();
}
return $RESULT;
}
使用 mysqlnd 你通常會這樣做:
$Statement = $Database->prepare( 'SELECT x FROM y WHERE z = ?' );
$Statement->bind_param( 's', $z );
$Statement->execute();
$Result = $Statement->get_result();
while ( $DATA = $Result->fetch_array() ) {
// Do stuff with the data
}
并且沒有mysqlnd:
$Statement = $Database->prepare( 'SELECT x FROM y WHERE z = ?' );
$Statement->bind_param( 's', $z );
$Statement->execute();
$RESULT = get_result( $Statement );
while ( $DATA = array_shift( $RESULT ) ) {
// Do stuff with the data
}
所以用法和語法幾乎相同.主要區(qū)別在于替換函數(shù)返回的是結(jié)果數(shù)組,而不是結(jié)果對象.
So the usage and syntax are almost identical. The main difference is that the replacement function returns a result array, rather than a result object.
這篇關(guān)于Mysqli get_result 替代方案的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!