Your First MySQL example
Connect and Display using PHP
This will connect to the database samplelinks and then display all the information in the links table in an HTML table on your page . You will have to replace the localhost , yourname and password with your own information .
<?php
//connect to database using the mysql_connect function()
//This is your host and then your username and then
//finally your password
$db = mysql_connect("localhost","yourname","password");
//The function mysql_select_db() sets the current
//databse to the one specified in this case "samplelinks"
mysql_select_db("samplelinks" ,$db);
//mysql_query() execute the specified MySQL query in this case
//we are are storing this in the variable $sqlquery
$sqlquery = mysql_query("SELECT * FROM links" ,$db);
//now we wil start producing a table
echo ("<table border ='1'>");
//this part displays our headings
echo ("<tr><td>url</td><td>description</td></tr>");
//the mysql_fetch_row() function fetches the next row in the resultset
//and stores this in an array , in this case $tablerows
while ($tablerows = mysql_fetch_row($sqlquery))
{
//we now finish our table off by inserting values into each
//column . $tablerows[0] is equivalent to our url field and
//$tablerows[1] is the description field
echo("<tr><td>$tablerows[0]</td><td>$tablerows[1]</td></tr> ");
}
//close the database
echo "</table>";
?>
and that is the complete code for this example , this is what you should see in your page with the code in it .
Now some people may be dissapointed to see that the links do not work , well we make the following alteration to the code above and this will rectify this.
echo("<tr><td><a href='$tablerows[0]'>$tablerows[0]</a></td><td>$tablerows[1]</td></tr> ");
and now we will see this instead .

In the next tutorials we will add and delete records using this database
Back to Part 1
|