Home > Backend Development > PHP Tutorial > How to Replace mysql_result() with MySQLi in PHP?

How to Replace mysql_result() with MySQLi in PHP?

Linda Hamilton
Release: 2024-12-07 20:10:14
Original
153 people have browsed it

How to Replace mysql_result() with MySQLi in PHP?

MySQLi Equivalent of mysql_result()

While transitioning PHP code from mysql to MySQLi, the absence of an equivalent to mysql_result() can pose a minor obstacle. This function allowed developers to retrieve a single value from a query result.

Solution:

Despite the lack of a direct equivalent, a custom function can replicate the functionality of mysql_result():

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;
}
Copy after login

This function:

  • Replicates the behavior of mysql_result().
  • Returns false if the request is out-of-bounds (empty result, non-existent row or column).
  • Assumes row 0 and column 0 (one less value to pass) if they are not specified.
  • Allows for the numerical offset of the field or the field name.

Example:

To use the function, simply replace the mysql_result() call with the following:

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

Note:

This custom function excels when working with a single result and field, allowing for concise code. However, for larger datasets, it's still recommended to use the more efficient fetch_assoc() method.

The above is the detailed content of How to Replace mysql_result() with MySQLi in PHP?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template