hide a passed vaiable id from url to avoid SQL injection
Posted: Mon Nov 14, 2005 6:39 am
Hi I've been looking into creating dynamic news publisher that utilises MySql, the code that I hacked together from two good tutorials passes the variable id of each news story/content in the URL and I need to hide this to avoid SQL injection. Does anybody have a quick answer how to do this?
The code for list.php
The code for the story.php to which this id is passed is:
Your help is greatly appreciated
The code for list.php
Code: Select all
<?
// list.php - display list of five most recent press releases
?>
<!-- page header - snip -->
<ul>
<?
// includes
include("conf.php");
include("functions.php");
// open database connection
$connection = mysql_connect($host, $user, $pass) or die ("Unable to
connect!");
// select database
mysql_select_db($db) or die ("Unable to select database!");
// generate and execute query
$query = "SELECT id, slug, timestamp FROM news ORDER BY timestamp DESC
LIMIT 0, 5";
$result = mysql_query($query) or die ("Error in query: $query. " .
mysql_error());
// if records present
if (mysql_num_rows($result) > 0)
{
// iterate through resultset
// print article titles
while($row = mysql_fetch_object($result))
{
?>
<li><font size="-1"><b><a href="story.php?id=<? echo $row->id;
?>"><?
echo $row->slug; ?></a></b></font>
<br>
<font size="-2"><? echo formatDate($row->timestamp); ?></font>
<p>
<?
}
}
// if no records present
// display message
else
{
?>
<font size="-1">No press releases currently available</font>
<?
}
// close database connection
mysql_close($connection);
?>
</ul>
<!-- page footer - snip -->Code: Select all
<?
// story.php - display contents of selected press release
?>
<!-- page header - snip -->
<?
// includes
include("conf.php");
include("functions.php");
// open database connection
$connection = mysql_connect($host, $user, $pass) or die ("Unable to
connect!");
// select database
mysql_select_db($db) or die ("Unable to select database!");
// generate and execute query
$id = $_GET['id'];
echo $id;
$query = "SELECT slug, content, contact, timestamp FROM news WHERE id =
'$id'";
$result = mysql_query($query) or die ("Error in query: $query. " .
mysql_error());
// get resultset as object
$row = mysql_fetch_object($result);
// print details
if ($row)
{
?>
<p>
<b><? echo $row->slug; ?></b>
<p>
<font size="-1"><? echo nl2br($row->content); ?></font>
<p>
<font size="-2">This press release was published on <? echo
formatDate($row->timestamp); ?>. For more information, please contact <?
echo $row->contact; ?></font>
<?
}
else
{
?>
<p>
<font size="-1">That press release could not be located in our
database.</font>
<?
}
// close database connection
mysql_close($connection);
?>
<!-- page footer - snip -->Your help is greatly appreciated