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');
The desired MySQLi equivalent would take the form:
if ($r && $r->num_rows) $blarg = $r->result(0, 'blah');
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 && $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; }
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!