Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQLi equivalent of mysql_result()?

Tags:

php

mysqli

I'm porting some old PHP code from mysql to MySQLi, and I've ran into a minor snag.

Is there no equivalent to the old mysql_result() function?

I know mysql_result() is slower than the other functions when you're working with more than 1 row, but a lot of the time I have only 1 result and 1 field. Using it lets me condense 4 lines into 1.

Old code:

if ($r && mysql_num_rows($r))       $blarg = mysql_result($r, 0, 'blah'); 

Desired code:

if ($r && $r->num_rows)       $blarg = $r->result(0, 'blah'); 

But there is no such thing. :(

Is there something I'm missing? Or am I going to have to suck it up and make everything:

if ($r && $r->num_rows)   {       $row = $r->fetch_assoc();       $blarg = $row['blah'];   } 
like image 752
DOOManiac Avatar asked Jan 18 '10 22:01

DOOManiac


People also ask

What is Mysql_result?

The mysql_result() function returns the value of a field in a recordset. This function returns the field value on success, or FALSE on failure.

What is the output of Mysqli_query?

Mysqli_connect doesn't target the table and mysqli_query doesn't output anything.


1 Answers

While answered, I thought I could improve on the answer given after having the same question. The following function fully replicates the mysql_result() function, and returns false when you are out-of-bounds on your request (empty result, no row of that number, no column of that number). It does have the added benefit that, if you don't specify the row, it assumes 0,0 (one less value to be passed). The function was updated to allow for the numerical offset of the field or the field name.

function mysqli_result($res,$row=0,$col=0){      $numrows = mysqli_num_rows($res);      if ($numrows && $row <= ($numrows-1) && $row >=0){         mysqli_data_seek($res,$row);         $resrow = (is_numeric($col)) ? mysqli_fetch_row($res) : mysqli_fetch_assoc($res);         if (isset($resrow[$col])){             return $resrow[$col];         }     }     return false; } 
like image 64
Mario Lurig Avatar answered Sep 30 '22 23:09

Mario Lurig