MySQLi equivalent of mysql_result()?

Viewed 65234

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

Well, you can always shorten it to something like this:

if ($r && $r->num_rows)
    list($blarg) = $r->fetch_row();

But that might be as good as you're going to get.

You don't need mysql_result() or any similar function.

If you would like to access any column from any row in the result set, the best way is to fetch all into an array using mysqli_fetch_all().

$data = $result->fetch_all(MYSQLI_BOTH);
$var1 = $data[0]['column']; // column from the first row
$var2 = $data[1][2]; // third column from the second row

To prevent access to non-existent values, you can use the null-coalesce operator and provide default value. e.g. $data[1][2] ?? null;.

As of PHP 8.1, mysqli also offers method called fetch_column(). You can use it if you only want to fetch a single value from the result.

$value = $mysqli->query("SELECT email FROM users WHERE userid = 'foo'")->fetch_column(0);

Here's an adaptation of Mario Lurig's answer using a mysqli_result object instead of the procedural version of mysqli.

/**
 * Accepts int column index or column name.
 *
 * @param mysqli_result $result
 * @param int $row
 * @param int|string $col
 * @return bool
 */
function resultMysqli(mysqli_result $result,$row=0,$col=0) { 
    //PHP7 $row can use "int" type hint in signature
    $row = (int)$row; // PHP5 - cast to int
    if(!is_numeric($col) ) { // cast to string or int
        $col = (string)$col;
    } else {
        $col = (int)$col;
    }
    $numrows = $result->num_rows;
    if ($numrows && $row <= ($numrows-1) && $row >=0) {
        $result->data_seek($row);
        $resrow = (is_numeric($col)) ? $result->fetch_row() : $result->fetch_assoc();
        if (isset($resrow[$col])){
            return $resrow[$col];
        }
    }
    return false;
}
Related