Adding Lopp To Get Code

Hi,

I have a get code which gets an article category however it only returns 1 article. I am trying to add a loop so that it runs through the whole ‘articlecategory’ and returns every article under the key word.

Can anyone advise the best route to go down or what type of of loop to use please.

<?php
if (isset($_GET['articlecategory']))
$articlecategory = mysql_real_escape_string($_GET['articlecategory']);
$sql = "SELECT * FROM articles WHERE articlecategory = '$articlecategory' ORDER BY ID DESC LIMIT 15";
$res = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_assoc($res); // no need to loop since you are retrieving only one row
$num_rows = mysql_num_rows($res); // check to see if any results were found, just in case someone puts an ID in the url without clicking on your link
?>

If you’re wanting to get more than one result, then you should use the while loop upon the mysql_fetch_assoc() function:


<?php
if (isset($_GET['articlecategory']))
{
    $articlecategory = mysql_real_escape_string($_GET['articlecategory']);
    $res = mysql_query("SELECT * FROM articles WHERE articlecategory = '{$articlecategory}' ORDER BY ID DESC LIMIT 15") or die(mysql_error());
    if($res && mysql_num_rows($res) > 0)
    {
        while($row = mysql_fetch_assoc($res))
        {
            #output data here
        }
    }
}
?>

I cleaned up the PHP a bit, along with reordering your use of mysql_num_rows() which, rather pointlessly, came up after the fetching of the rows data (which could potentially not exist).

It may also be a good idea to whitelist the article categories, so that you can check if a correct category is actually being used before querying your database with it.

Brilliant, that worked straight away.

What do you mean by whitelist?

Make sure the associative array $_GET data matches up against a set list of category names. That way you only allow queries that you know will have a successful return.

E.g.1


<?php
$whitelist = array('php', 'html', 'ruby', 'perl');
if(in_array(strtolower($_GET['category']), $whitelist))
{
    $cat = strtolower($_GET['category']);
}
else
{
    $cat = 'php'; #defult value
}
?>

E.g.2


<?php

switch(strtolower($_GET['category']))
{
    case 'php':
    case 'html':
    case 'ruby':
    case 'perl':
    $cat = strtolower($_GET['category']);
    break;
    default:
    $cat = 'php';
}
?>