Jump to content

[SOLVED] News article - using the subject as a hyperlink


beerguts

Recommended Posts

Hi All,

 

I am setting up news articles on the front page of my website so that only the date and subject of the article is displayed as a hyperlink.  When the user clicks on the hyperlink they are directed to a page which displays the whole article.

 

I have created the code for the front page no problem:

 

$result = mysql_query("SELECT news_title, news_body, news_id, DATE_FORMAT(news_date, '%D %b %Y') AS 
formattedRacedate FROM news ORDER BY news_id DESC LIMIT 10 ")or die(mysql_error());

while($article=mysql_fetch_array($result))
  {
echo "<tr>";
echo "<td width=100px valign='top'>".$article['formattedRacedate']."</td>";
        echo '<td><a href="news.php?article=' . $article['news_id'] . '">'. $article['news_title'] . '</a></td>';
echo "</tr>";
	}

echo "</table>";

 

 

this is where my limited PHP knowledge starts to dry up!

 

What code do I need for "news.php" to ensure the correct article is displayed?  The URL is correctly displaying the news_id at the end.

 

 

Thanks in advance for your help :)

 

 

First you'd get the article id from the URL using the $_GET super-global, then after securing the variable (with mysql_real_escape_string()) setting up a query to return the information from that article.

 

Like so:

 

$article_id = mysql_real_escape_string($_GET['article']);
$result = mysql_query("SELECT news_title, news_body, news_id, DATE_FORMAT(news_date, '%D %b %Y') AS 
formattedRacedate FROM news WHERE news_id='$article_id'")or die(mysql_error());
$row = mysql_fetch_assoc($result); // Not a loop because it's only 1 record

echo $row['news_body']; // The whole article

 

You can then format it anyway you want.

 

Preferably you should also preform a check first to make sure that an article by that id really exists, like so:

 

$article_id = mysql_real_escape_string($_GET['article']);
$result = mysql_query("SELECT news_title, news_body, news_id, DATE_FORMAT(news_date, '%D %b %Y') AS 
formattedRacedate FROM news WHERE news_id='$article_id'")or die(mysql_error());
if(!mysql_num_rows($result))
{
      //Article doesn't exist
}
else
{
     $row = mysql_fetch_assoc($result); // Not a loop because it's only 1 record
     echo $row['news_body']; // The whole article
}

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.