0

Can anyone offer any suggestions on how to secure this PHP script from sql injection:

 <?php
include("config.php");
if(isset($_POST['lastmsg']))
{
$lastmsg = mysqli_real_escape_string($_GET['lastmsg']);
$result=mysql_query("select * from messages where msg_id<'$lastmsg' order by msg_id desc limit 9");
$count=mysql_num_rows($result);
while($row=mysql_fetch_array($result))
{
$msg_id=$row['ms_gid'];
$message=$row['message'];
?>



<li>[
<?php echo $message; ?>
</li>


<?php
}


?>

<div id="more<?php echo $msg_id; ?>" class="morebox">
<a href="#" id="<?php echo $msg_id; ?>" class="more">more</a>
</div>

<?php
}
?>

Thanks :)

3
  • is 'lastmsg' a POST or GET variable? You've referenced it two different ways. Commented Apr 15, 2011 at 19:26
  • Its a post, sorry just noticed that. Thanks :) Commented Apr 15, 2011 at 19:29
  • 1
    PDO. Learn it, use it. Commented Apr 15, 2011 at 19:54

2 Answers 2

4
$lastmsg = mysqli_real_escape_string($_GET['lastmsg']);

If you have access to mysqli you should use it in preference to mysql, because it allows you to bind parameters to statements thus bypassing SQL injection attacks. Sample code in procedural style:

$link = mysqli_connect();
$stmt = mysqli_stmt_init($link);
mysqli_stmt_prepare($stmt, "select * from messages where msg_id < ? order by msg_id desc limit 9");
mysqli_stmt_bind_param($stmt, "s", $_GET['lastmsg']);
mysqli_stmt_execute($stmt);
mysqli_stmt_store_result($stmt);
$count = mysqli_stmt_num_rows($stmt);
Sign up to request clarification or add additional context in comments.

Comments

0

mysql_real_escape_string() is the only thing you need. Pass any value you're going to insert into the database through that first.

$someval = mysql_real_escape_string($someval);
$query = "SELECT ... WHERE field='$someval'";

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.