Is There a MySQLi Equivalent to the mysql_result() Function?

Susan Sarandon
Release: 2024-11-24 18:34:16
Original
278 people have browsed it

Is There a MySQLi Equivalent to the mysql_result() Function?

Is There an Equivalent to MySQLi's mysql_result() Function?

In the process of migrating PHP code from MySQL to MySQLi, developers often encounter the absence of the mysql_result() function. While it is acknowledged that mysql_result() becomes less efficient when handling multiple rows, its convenience for scenarios involving a single result and field is undeniable.

Originally expressed in the following code snippet:

if ($r && mysql_num_rows($r))
    $blarg = mysql_result($r, 0, 'blah');
Copy after login

The desired MySQLi equivalent would take the form:

if ($r && $r->num_rows)
    $blarg = $r->result(0, 'blah');
Copy after login

However, such a function does not exist in MySQLi's default repertoire.

Addressing the Void

To bridge this gap, a custom function has emerged that replicates the functionality of mysql_result():

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

This function retains the inherent convenience of mysql_result() by employing the identical syntax. It returns false if the specified row or field falls outside the result set, ensuring reliable data retrieval. Additionally, it accommodates both numerical field offsets and field names for enhanced flexibility.

The above is the detailed content of Is There a MySQLi Equivalent to the mysql_result() Function?. 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