php - Sql注入(inject)获取id解决方案

标签 php mysql

我不知道如何保证此代码的安全。我尝试在查询变量中使用 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/

相关文章:

php - 将数据库的每一行值与我自己的值进行比较

sql - MySQL 从日期列中获取每个月的最后一个日期

c# - 无法从 ASP.NET 连接到 MySQL 数据库

mysql - SQL:加入2个表并将id更改为用户名

php - 函数未按预期返回数据

PHP strtotime 将 false 保存为 MySQL 负整数

javascript - Laravel 4-重定向到 JavaScript 代码 Blade 模板中的路由

php - Google Glass 开发错误 : (403) Access Not Configured. 请使用 Google Developers Console 为您的项目激活 API

sql - 这两个 MySQL 查询中哪个更有效?

mysql - 存储具有特定查看权限的用户之间的关系