PHP and MySQL Basics
Now that we have a bunch of articles, we need to be able to view them. There are two methods of pulling data from MySQL that I am going to cover, the first is pulling multiple rows in a loop, for example displaying a list of your articles. Make sure you have added some test articles before trying this.
<?
// connect to mysql and select database
$db = mysql_pconnect("localhost","USER","PASS");
mysql_select_db("DATABASENAME",$db);
// build the query, order by newest ID and limit it to 10
$sql = "SELECT * FROM news ORDER BY id DESC LIMIT 10";
// run the query and set a result identifier to the recordset
$res = mysql_query($sql);
// loop the recordset
while ($article = mysql_fetch_array($res)) {
// this sticks the results row by row into an array called $article. rows are called via $array["COLUMN"]
echo '<b>'.$article["posted"].' - Author: '.$article["author"].'</b><br>'.$article["content"].'<br><br>';
}
?>
SELECT * FROM articles tells MySQL that we want all the columns from all the entries in the database. ORDER BY id DESC tells it to order them by the id column in descending order, and LIMIT 10 tells it that we only want the first 10.
If you want to pull the next 10 results, you use limit 10,10 instead. This tells MySQL to pull the first 10 results, starting at the 10th result. We then set the variable $res to equal the output of the query. To take this result and put it into an array that we can work with, we use mysql_fetch_array().
The while loop continues doing this untill $article does not equal mysql_fetch_array anymore, which means there it has gone through all the results that mysql selected from the database. This also means that we have finished and got all 10 rows. Now we have a page with the 10 most recent articles.
