Home >Backend Development >PHP Tutorial >How to Replace PHP\'s `mysql_result()` Function with MySQLi?

How to Replace PHP\'s `mysql_result()` Function with MySQLi?

Linda Hamilton
Linda HamiltonOriginal
2024-11-25 13:29:11918browse

How to Replace PHP's `mysql_result()` Function with MySQLi?

How to Replicate the Functionality of PHP's mysql_result() Function in MySQLi

The mysql_result() function, commonly used in legacy PHP code, enables developers to quickly access specific data from a MySQL query result. However, this function is not natively supported in MySQLi, the improved and recommended extension for interacting with MySQL databases.

Alternative Approach with Fetching Rows

One common approach to retrieving data from MySQLi query results is to fetch the corresponding row using the fetch_assoc() method. Here's an example:

if ($r && $r->num_rows) {
    $row = $r->fetch_assoc();
    $blarg = $row['blah'];
}

This approach involves multiple lines and can be less efficient than using a dedicated function like mysql_result().

Custom Equivalent Function

To replicate the functionality of mysql_result() in MySQLi, you can create a custom function as shown below:

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

This function accepts row and column indices as parameters and returns the corresponding data if it exists. It also handles potential errors related to out-of-bounds requests.

Usage:

The mysqli_result() function can be used in a similar way to mysql_result():

if ($r && $r->num_rows)  
    $blarg = mysqli_result($r, 0, 'blah');

Benefits and Limitations

The custom mysqli_result() function allows for more concise code and reduces the number of lines required to retrieve data from MySQLi query results. However, it should be noted that this function relies on PHP's dynamic function invocation and may incur a small performance penalty compared to the original mysql_result() implementation.

The above is the detailed content of How to Replace PHP\'s `mysql_result()` Function with MySQLi?. 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