In this tutorial, we’ll see how to display the contents of mysql table in your php webpage. In my previous tutorial of webserver setup, we checked out how to setup xampp or uniform server. Now you can use the phpmyadmin or sql console from these web server to perform database operations with your webpage.
What we’re going to do?
- Establish connection with database.
- Create an object (or reference) that holds the contents of database.
- Perform action on database (like reading or writing).
- Close the connection or Display the results.
So now we’ve a goal to display the contents of the database with the help of php and mysql. Let’s first start with the database creation.
You can use phpmyadmin to create a database and populate the table with entries. I have created a database called contacts and inside it there is table called bizcard. There are three fields – No, Name, Surname. We’re going to make “No” a primary key. Right now we’re not worried about auto-increment and other stuff. So let’s just keep it as it is.
Now let’s write PHP code to fetch the content of our database “contacts”. Here is the code –
< ?php // Connects to your Database mysql_connect("localhost", "root", "root") or die(mysql_error()); mysql_select_db("contacts") or die(mysql_error()); $data = mysql_query("SELECT * FROM bizcard") or die(mysql_error()); while($row = mysql_fetch_assoc($data)){ echo "No: ".$row['No'].", Name:".$row['Name'] .", Surname:".$row['Surname']."<br/>"; } ? >
First we’re connecting to the mysql server and for that we’re adding the credentials like – “name of the server” : localhost and username and password. My credentials and your web servers credentials will vary, so you have to check with xampp or uniform server on your desktop. In second part we’re connecting to the table if the previous connection to the database is successful. If there is any error in these two steps, mysql error will be thrown on webpage.
In third step, we’re creating an object or reference that fetches the content of our table ‘bizcard’. We’re now placing the cursor on each row and printing out the content of database. Based on the content inside the table, you’ll see the result in output. Make sure you don’t make mistakes here or else there will be mysql error thrown for your invalid syntax.