Home >Backend Development >PHP Tutorial >How Can I Replace PHP\'s `mysql_result()` Function with a MySQLi Equivalent?

How Can I Replace PHP\'s `mysql_result()` Function with a MySQLi Equivalent?

Barbara Streisand
Barbara StreisandOriginal
2024-12-02 20:34:12676browse

How Can I Replace PHP's `mysql_result()` Function with a MySQLi Equivalent?

PHP MySQLi Equivalent to mysql_result()

In upgrading PHP code from MySQL to MySQLi, you may encounter the absence of the frequently used mysql_result() function. While slower for multiple rows and columns, mysql_result() often proves convenient for single-result scenarios.

Addressing the Gap

Contrary to initial impressions, there is indeed an equivalent to mysql_result() for MySQLi. The solution involves creating a custom function that replicates its functionality.

Custom Result Function

The following code provides a full-featured replacement for mysql_result(), including:

  • Row and column index specification (numerical or field name)
  • Default assumption of 0,0 for unspecified parameters
  • False return for out-of-bounds requests
function mysqli_result($res,$row=0,$col=0) { 
    $numrows = mysqli_num_rows($res); 
    if ($numrows &amp;&amp; $row <= ($numrows-1) &amp;&amp; $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;
}

Implementation

To use the custom function, simply replace instances of mysql_result() in your old code with the following syntax:

$blarg = mysqli_result($r, 0, 'blah');

Conclusion

The provided custom function empowers you to retain the convenience of the mysql_result() function while leveraging the benefits of MySQLi. Enjoy seamless code migration without sacrificing functionality or efficiency.

The above is the detailed content of How Can I Replace PHP\'s `mysql_result()` Function with a MySQLi Equivalent?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn