-1

I'm using mysqli instead of mysql, and came across the error Call to undefined function mysqli_result()

From looking on Google, the general consensus is that mysql_result was a useless function anyway and there is no need for it in the MySQLi library. However, I think it is useful and can't see what's wrong with the following code?

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

Is there a way to replicate the way mysql_result worked without changing the code too much?

cantsay
  • 1,967
  • 3
  • 21
  • 34

2 Answers2

0

You could implement it yourself,

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

mysql_result's popularity came from people who only needed to access a single row or field. As of PHP 5.4, array dereferencing support has now been added, so you can do:

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

So in your example, you could instead do

while ($exists->fetchassoc()[0] === 1);
kba
  • 19,333
  • 5
  • 62
  • 89
  • thanks, `while (mysqli_fetch_assoc($exists)[0] === 1);` worked perfectly. – cantsay Dec 16 '13 at 04:12
  • the only mysql_result's popularity came from tutorials written in the last century. @cantsay you better learn some not *that old* practice instead of trying to use it with new API – Your Common Sense Dec 16 '13 at 07:06
-1

In this specific instance, you could use:

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

As for other instances where you may want to use mysql_result, the documentation suggests:

  • mysqli_data_seek() in conjunction with mysqli_field_seek() and mysqli_fetch_field()
  • PDOStatement::fetchColumn()

Cycling through to an arbitrary row in PHP may be confusing. I think it would make more sense to use LIMIT/OFFSET in the query itself.

Explosion Pills
  • 188,624
  • 52
  • 326
  • 405