How to display data from a MySQL database – PHP Script

PHP is a widely used and easiest language in the world.

It’s very simple to display the data from a MySQL table to a webpage using PHP scripting.

First, you need to create a database and a table in MySQL. You can learn by watching this video or Click here to Read an Article.

After you create a database and a table. You insert some values in it.

Let’s say our table looks like this now:

Database name:    mydatabase
Table name:           mytable

Id

name

city

1

Agurchand

Bangalore

2

Abhiesheik

Chennai

3

Balaji

Madurai

Then use the below code to fetch records from the database and show it on the webpage!

<?php

$mysqli = new mysqli("localhost","root","","yourdb");

// Check connection
if ($mysqli->connect_errno) {
  echo "Failed to connect: " . $mysqli->connect_error;
  exit();
}

echo "<table border=1>";
echo "<tr><th>User Id</th><th>Fullname</th><th>City</th>";
// query a table
if ($result = $mysqli->query("SELECT * FROM users")) {
  while ($row = $result->fetch_assoc() ){
    echo "<tr><td>$row[user_id]</td><td>$row[fullname]</td><td>$row[city]</td></tr>";
  }
  $result -> free_result();
}

echo "</table>";

$mysqli->close();

?>

I hope you enjoy learning new things daily. Practical Experiment is the only way of learning stuff quickly and powerfully.

5 thoughts on “How to display data from a MySQL database – PHP Script

  1. finally, thank godness i found yor site..thank you soo much! i’ve been lookin’ for this kind of code so many times, but others did’nt work..thanks3!!!

  2. Thank you, thank you, thank you!!! I have really been struggling with php because I’m a newbie. I desperately needed something like this for my school project and you have really saved me. I know I will get much better with practice and hope one day to be able to help people as you have done here. Thanks again!

Leave a Reply

Theme: Overlay by Kaira
Agurchand