Subject: Chapter 13 - CMS
Posted By: gedgecc Post Date: 7/11/2008 5:42:16 AM
Hi all, I'm working on the CMS chapter and I've got it working perfectly, however is there a way which I can control the number of published arcticles that show up on the home page. At the moment it's unlimited and only shows the first few lines of a published article. I only want to show the title of the article and perhaps only the last four published.

here's the code

<?php
require_once 'conn.php';
require_once 'outputfunctions.php';


$sql = "SELECT article_id FROM cms_articles WHERE is_published=1 " .
       "ORDER BY date_published DESC";

$result = mysql_query($sql, $conn);

if (mysql_num_rows($result) == 0) {
  echo "  <br><h5>";
  echo "  There are currently no articles to view.<h5>";
} else {
  while ($row = mysql_fetch_array($result)) {
    outputStory($row['article_id'], TRUE);
  }
}


?>

Any advice would be cool, thanks in advance

Reply By: andychamberlainuk Reply Date: 7/28/2008 7:05:12 PM
Hi,

There are a few ways in which you can do this: -

1) Place a variable before the while loop (e.g. $i) and have it so the variable counts up by one each loop. Then, just set your maximum number of articles and when it reaches that number, just break from the loop.

e.g.

if (mysql_num_rows($result) == 0) {
  echo "  <br><h5>";
  echo "  There are currently no articles to view.<h5>";
} else {
$i=0;
  while ($row = mysql_fetch_array($result)) {
    $i++;
    outputStory($row['article_id'], TRUE);
    if ($i==5) break;
  }
}

2) Place a limit in your query

e.g.

$limit=5;
$sql = "SELECT article_id FROM cms_articles WHERE is_published=1 " .
       "ORDER BY date_published DESC LIMIT 1,$limit";

If you want to show the total number of articles, you need to modify the SQL code to this: -

$limit=5;
$sql = "SELECT SQL_CALC_FOUND_ROWS article_id FROM cms_articles WHERE is_published=1 " .
       "ORDER BY date_published DESC LIMIT 1,$limit";
$result = mysql_query($sql, $conn);

$sql2 = "SELECT FOUND_ROWS()";
$result2 = mysql_query($sql2, $conn);
$row2 = mysql_fetch_array($result2);
$numrows = $row2['0'];

The first method will be easier to integrate and is much easier to understand!

Hope this helps





Go to topic 73073

Return to index page 1