有没有办法使用mysqli(程序)复制mysql_result?

时间:2013-12-16 03:56:43

标签: php mysql mysqli

我正在使用mysqli而不是mysql,并遇到了错误Call to undefined function mysqli_result()

从Google上看,普遍的共识是mysql_result无论如何都是无用的功能,并且在MySQLi库中不需要它。但是,我觉得它很有用,看不出以下代码有什么问题?

do
{
    $id = rand_id();
    $exists = mysql_query('SELECT EXISTS(SELECT 1 FROM `files` WHERE `name` = "' . $id . '")');
}
while (mysql_result($exists, 0) === 1);

有没有办法在不改变代码的情况下复制mysql_result的工作方式?

2 个答案:

答案 0 :(得分:0)

您可以自己实施,

function mysqli_result($res, $row, $field=0) { 
    $res->data_seek($row); 
    $datarow = $res->fetch_array(); 
    return $datarow[$field]; 
}

mysql_result的受欢迎程度来自只需要访问单行或字段的人。从PHP 5.4开始,array dereferencing support现已添加,您可以这样做:

$result->fetch_assoc()['field'];

所以在你的例子中,你可以改为

while ($exists->fetchassoc()[0] === 1);

答案 1 :(得分:0)

在此特定实例中,您可以使用:

do {
    $id = rand_id();
    $exists = mysqli_query("SELECT 1 FROM files WHERE name = $id");
} while (mysqli_num_rows($exists));

对于您可能想要使用mysql_result的其他情况,文档建议:

  
      
  • mysqli_data_seek()mysqli_field_seek()mysqli_fetch_field()
  • 一起使用   
  • PDOStatement::fetchColumn()
  •   

循环到PHP中的任意行可能会令人困惑。我认为在查询本身中使用LIMIT / OFFSET会更有意义。