Connect to MySQL Database and display first 5 results using PHP
9
Connect to MySQL db & display result from Table query
<?php
$username = "your_username";
$password = "your_password";
$db = "database_name";
//for anyone with a local server the $host can be set to "localhost" or "127.0.0.1"
$host = "host_address";
$db_connection = mysql_connect($host, $username, $password) or die("Could not connect");
$MySQLSelectedDB = mysql_select_db($db, $db_connection) or die("Could not set the Database");
$res=mysql_query("SELECT * FROM table_name LIMIT 5");
//check that there is something in the table to display
if (mysql_num_rows($res)==0) {
echo "There is no data in the table";
} else {
//extract the data and print it out with a simple echo for each field
for($i=0; $i<mysql_num_rows($res); $i++) {
$row=mysql_fetch_assoc($res);
echo "Field 1 : $row[field_1] Field 2 : $row[field_2] Field 3 : $row[field_3] </BR>";
}
}
//close connection
mysql_close($db_connection);
?>






What is that part used for? You seem to be doing a select query on a database, instead of a table... ?
A more common approach for fetching data would be this:
while ($row = mysql_fetch_assoc($res)) {
....
}
There seems no need to make a loop count over them when something like this is cleaner and clearer...
What is < / BR > ?
Just a few pennies worth