我不知道如何保证此代码的安全。我尝试在查询变量中使用 mysql_real_escape_string ,例如
$query = "select * from products where id= " . mysql_real_escape_string($products);
<?php
/ Define vars.
$conn = mysql_connect('localhost', 'test', 'test');
$products = isset($_GET["products"]) ? $_GET["products"] : "";
$query = "select * from products where id=$products";
// List elements.
if ($conn)
{
mysql_select_db('testsqli');
$result = mysql_query($query);
// Table head.
echo '<table cellspacing="5" cellpadding="5">';
echo '<tr>';
echo '<td>Description</td>';
echo '<td>Price</td>';
echo '</tr>';
// Empty table?
if (@mysql_num_rows($result)==0)
{
echo '<tr>';
echo '<td><i>That\'s all!</i></td>';
echo '</tr>';
}
// Listing data in table.
while ($row = @mysql_fetch_array($result))
{
echo '<td>'.$row['Description'].'</td>';;
echo '<td>'.$row['Price'].'</td>';;
}
echo '</table>';
}
?>
最佳答案
您仍然需要添加引号(并使用 msqli 代替),例如:
$query = "select * from products where id='" . mysqli_real_escape_string($products)."'";
// or
$query = sprintf(
"select * from products where id='%s'",
mysqli_real_escape_string($products)
);
关于php - Sql注入(inject)获取id解决方案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28975346/