Change mysql_result to mysqli?

I have an older site with the older mysql. It seems like this is going to be changed to mysqli in the future on the newer versions of PHP.

It seems like there is no similar function to mysql_result for mysqli. I have a piece of code looking like this on the older version


$QUERY = mysql_query("SELECT * FROM categories");
$NUMROWS = mysql_num_rows($QUERY);

if ($NUMROWS) {
$I = 0;

while ($I < $NUMROWS) {
	
$cat_id = mysql_result($QUERY,$I,"cat_id");
$cat_number = mysql_result($QUERY,$I,"cat_number");
$cat_name = mysql_result($QUERY,$I,"cat_name");
$cat_rank = mysql_result($QUERY,$I,"cat_rank");
         
// DISPLAY CATEGORY LIST **********************************
echo "$cat_id"; 
echo "$cat_number"; 
echo "$cat_name"; 
echo "$cat_name"; 

$I++;

 }

}

I was wondering if someone knows how to make the above code working with mysqli

Thanks

Berra

You have to create your own.

function mysqli_result($res, $row, $field=0) { 
    $res->data_seek($row); 
    $datarow = $res->fetch_array(); 
    return $datarow[$field]; 
} 

I’m looking for the Procedural solution. Is this the OOP solution you showed?

Is there a procedural solution for this too?

There is no difference between OOP and procedural in this case as you are never going to need to touch the content of the function.

(In fact, this IS the procedural solution from your perspective, because you would procedural call the function, since you’re not implementing this function into a class, the function definition does not ‘attach’ to the mysql statement object)

1 Like

I got it to work with the code below which is just fetching my columns and rows and display. I’m not sure if this is bad code?..i’m not very advanced in php. Is there any security risk with the code below?

$con = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_DATABASE);

// Check connection
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }

//Query database
$query= mysqli_query($con, "SELECT * FROM categories");

$numrows= mysqli_num_rows($query);

if ($numrows){

$I = 1;
                
while($row = mysqli_fetch_assoc($query)){

$cat_name = $row['cat_name'];
$cat_num = $row['cat_num'];

echo "$cat_name, $cat_num, $I<br />";

$I++;

}
}
?>

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.