I'm porting some old PHP code from mysql to MySQLi, and I've ran into a minor snag.
Is there no equivalent to the old mysql_result()
function?
I know mysql_result()
is slower than the other functions when you're working with more than 1 row, but a lot of the time I have only 1 result and 1 field. Using it lets me condense 4 lines into 1.
Old code:
if ($r && mysql_num_rows($r))
$blarg = mysql_result($r, 0, 'blah');
Desired code:
if ($r && $r->num_rows)
$blarg = $r->result(0, 'blah');
But there is no such thing. :(
Is there something I'm missing? Or am I going to have to suck it up and make everything:
if ($r && $r->num_rows)
{
$row = $r->fetch_assoc();
$blarg = $row['blah'];
}
My Answer:
= mysql_query("SELECT name FROM users WHERE id = 1")) {
$name = mysql_result($r, 0);
}
__New code using MySQLi:__
if ($r = $mysqli->query("SELECT name FROM users WHERE id = 1")) {
$row = $r->fetch_row();
$name = $row[0];
}
While there is no direct equivalent to mysql_result() in MySQLi, you can achieve the same result by using the fetch_row() method to fetch the result row as an enumerated array and then accessing the desired field directly from the array.
Rate this post
4 of 5 based on 3464 votesComments