Muhammed Karaoz Muhammed Karaoz - 5 months ago 9
MySQL Question

How can i convert this SQL code to MySQLi?

I've always been used to MySQL and recently it has become mandatory to use MySQLi in our college because MySQL is deprecated. For a project I have to convert a piece of code from MySQL to MySQLi but I'm struggling a lot. I was hoping somebody could help me?

The code retrieves data from the database and shows it on the home page as some sort of simple 'news page'.

<?php
require('connection.php');

if(!$alles = mysql_query("SELECT * FROM news ORDER BY Date DESC")){
die(mysql_error());
};

while ($art = mysql_fetch_array($alles))
{
//Nieuws
echo "<p><b>" .$art['Title']."</b></p>";
echo "<p>" .$art['Date']."</p>";
echo "<p>" .$art['Content']."</p>";
echo "<p><em>" .$art['Author']."</em></p>";
echo "<hr/>";
}
?>

Answer

Simply add connection string, and pass it in mysqli_query :

<?php
 //require('connection.php'); no need for this or add next line on that page

 $con=mysqli_connect('localhost',$dbuser,$dbpass,$dbname);

  $alles = mysqli_query($con,"SELECT * FROM news ORDER BY Date DESC");
  $count=mysqli_num_rows($alles);
  if($count > 0){ 
    while ($art = mysqli_fetch_array($alles))
    {
    //Nieuws
    echo "<p><b>" .$art['Title']."</b></p>";
    echo "<p>" .$art['Date']."</p>";
    echo "<p>" .$art['Content']."</p>";     
    echo "<p><em>" .$art['Author']."</em></p>";             
    echo "<hr/>";
    }
   }
?>
Comments