The First Steps In Making A Dynamic Website

Returning Data

Now we have the inserting code, we are ready to make a script that will get all the article names out of the database, and return them as links on another page. Again we'll do it in steps, as this is another part of PHP that can be hard to grasp.

To start with we'll connect and select the database that we're going to use. Once again, you replace "user", "pass" and "databasename" with the values that you used for the first page we made.


$connect = mysql_connect("localhost", "user", "pass");

mysql_select_db("databasename", $connect);

Next comes something new. We are going to write some code that will query the database and get everything out that we want. It reads like this:

$result = mysql_query("SELECT * FROM content ORDER BY ID",$connect);

To start with, a variable called $result is set to the query. The actual query selects everything (* means everything in SQL) from our table, and orders it by the ID's. A query doesn't produce anything, it's just a piece of code needed to SELECT what you need from the database. Notice we're also not setting an $sql variable this time. Instead we're specifying the SQL directly in the mysql_query() function.

So, onto the next stage. This can be quite hard to understand at first, but like most things in PHP, once you've read it a few times you should get the gist of what it means. Open your text editor again and enter the following. I will explain all afterwards.

while($row = mysql_fetch_array($result)){
		echo "<a href = 'article.php?aid=" . $row['ID'] . "'>" . $row['Name'] . "</a><br>";

Eh? What is this? Well it's not actually that complicated. We start off with what is called a while loop. This will loop through the MySQL result set (that we named $result above) until it is empty. It assigns the values in each row to an associative array called $row. An associative array is an array in which you can access variables by textual identifiers, rather than just their index number.

The next part displays (or echo's) the links. "<a href = 'article.php?id=" starts the link, with $row['ID'] pointing the link to the page with a specific ID. The final part ends the link, and creates the anchor text which will be the link name. Notice in the URL's query string we use "aid" instead of just "id." This is for SEO reasons as some search engines, like Google, do not like variables named "id."