MySQLi equivalent of mysql_result()?

DOOManiac picture DOOManiac · Jan 18, 2010 · Viewed 58.2k times · Source

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

Answer

Mario Lurig picture Mario Lurig · Jan 7, 2014

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;
}