Display data from MySQL with PHP

Posted by Shek on May 7, 2008 under PHP | Be the First to Comment | Total View: 11,430 views

Editor’s note: To display the data from MySQL database with PHP, we have to use the mysql_query( ) function to run a SQL query, here is a sample I have made to display all data from a table with 2 fields.

First we have to connect to database.

mysql_connect("Host Name", "User Name", "User Password") or die("Connection Failed");
mysql_select_db("DataBase Name")or die("Connection Failed");

Now we create the query for getting all the records from the table “table1” and we use a PHP variable to store the SQL query.

$query = "SELECT * FROM table1";

Now we run the query and we use a PHP variable to store the result of the SQL query.

$result = mysql_query($query);

We now use a while loop to go through the record 1 by 1 and keep doing so until the the result does not match the criteria of the query

while ($line = mysql_fetch_assoc($result)) {

Print out the data of field1 which matches the criteria of the query:

echo $line['field1'];

Print out the data of field2 which matches the criteria of the query:

echo $line['field2'];

Give a line feed after print out each record just to make it nicely displays.

echo "<br>\n";
}

All together we have:

1
2
3
4
5
6
7
8
9
10
11
<?php
mysql_connect("Host Name", "User Name", "User Password") or die("Connection Failed");
mysql_select_db("DataBase Name")or die("Connection Failed");
$query = "SELECT * FROM table1";
$result = mysql_query($query);
while ($line = mysql_fetch_assoc($result)) {
echo $line['field1'];
echo $line['field2'];
echo "<br>\n";
}
?>

Not what you want? Try a Search

Add A Comment

*