gpt4 book ai didi

php - Mysqli get_result 替代方案

转载 作者:IT王子 更新时间:2023-10-29 00:08:45 26 4
gpt4 key购买 nike

我刚刚使用 mysqli 将我所有的 sql 查询更改为准备好的语句。为了加快这个过程,我创建了一个函数(称为 performQuery)来代替 mysql_query。它接受查询、绑定(bind)(如“sdss”)和要传入的变量,然后执行所有准备好的语句。这意味着更改我所有的旧代码很容易。我的函数使用 mysqli get_result() 返回一个 mysqli_result 对象。

这意味着我可以更改我的旧代码:

$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'];
}

这在本地主机上运行良好,但我的网络托管服务器没有可用的 mysqlnd,因此 get_result() 不起作用。安装 mysqlnd 不是一个选项。

从这里出发的最佳方式是什么?我可以创建一个函数来替换 get_result() 吗?如何创建?

最佳答案

这是一个基于与 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
}

因此用法和语法几乎相同。主要区别在于替换函数返回结果数组,而不是结果对象。

关于php - Mysqli get_result 替代方案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10752815/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com