Tag Archives: mysql_result

mysqli_result() function to match mysql_result()

This code is licensed under Creative Commons 0 (Public Domain)

As of PHP 5.5, the MySQL functions are deprecated and are removed in PHP 7. The recommendation is to switch to MySQLi functions, which conveniently offer both a procedural (my preference) and an object-oriented structure. Luckily, it’s a rather easy transition to MySQLi as functions names and functions are nearly identical (just change mysql_ to mysqli_). The only exception to this is the mysql_result() function, which has no analog.

Quick review: mysql_result() is used to write less code when your database query is returning only a single row (LIMIT 1) and/or a single column.

$output = mysql_result($result,0);

Pretty simple and straightforward. To replicate this in MySQLi, the following function can be used:

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

It has one improvement over mysql_result(), which is you can choose to only include the resource and no row and/or column. It will just assume mysqli_result($resource,0,0).

EDITED Dec 19, 2014
Function updated to allow for the column to be referenced by field name as well as numerical offset.