2

我有一个数据库表。我想进行文本输入,用户可以在其中输入“uid”,查询将返回与该 uid 关联的行。

所以假设我有这样的事情:

$query = "SELECT name,age FROM people WHERE uid = '2' LIMIT 0,1";
$result = mysql_query($query);
$res = mysql_fetch_assoc($result);

echo $res["age"];

我将如何将该查询修改为..

SELECT name, age 
  FROM people 
 WHERE uid = $_POST['blahblah'] LIMIT 0,1

在此先感谢您的帮助!

4

4 回答 4

5

事实上...

// Read input from $_POST
$uid = (isset($_POST['uid']) ? $_POST['uid'] : '');

// Build query.  Properly escape input data.
$query = 
  "SELECT name,age " .
  "FROM people " .
  "WHERE uid = '" . mysql_real_escape_string($uid) . "' " . 
  "LIMIT 0,1";

出于安全原因,建议对变量中的字符进行转义。看看这个文件有一些原因:

http://en.wikipedia.org/wiki/SQL_injection

于 2012-07-30T03:54:30.163 回答
3

要避免 SQL 注入攻击,请使用:

$search_query = mysql_real_escape_string($_POST['blahblah']);

$query  = "SELECT name, age FROM people WHERE uid = '".$search_query."' LIMIT 0 , 1";
于 2012-07-30T03:58:04.090 回答
0

有很多方法可以做到这一点但首先将其转义并将其存储在一个变量中

$blahblah = mysql_real_escape_string($_POST['blahblah']);

然后有

第一:正如@Mett Lo 提到的:

$query = "SELECT name,age FROM people WHERE uid = '" . $blahblah . "' LIMIT 0,1";

第二:

$query = "SELECT name,age FROM people WHERE uid = '{$blahblah}' LIMIT 0,1";

第三:

$query = "SELECT name,age FROM people WHERE uid = '$blahblah' LIMIT 0,1";

如果 blahblah 是 db 表中的 int 值,则第四:

$query = "SELECT name,age FROM people WHERE uid = $blahblah LIMIT 0,1";
于 2012-07-30T04:03:50.477 回答
0

您可以使用 sprintf 函数来创建查询。

$query = sprintf("SELECT name,age FROM people WHERE uid = '%s' LIMIT 0,1",
         $_POST['blahblah'] );

其余的将是相同的。强烈建议您在运行查询之前转义 $_POST 数据以防止 SQL 攻击。您可以将查询重新表述如下。

$query = sprintf("SELECT name,age FROM people WHERE uid = '%s' LIMIT 0,1",
         mysql_escape_string($_POST['blahblah']) );
于 2012-07-30T04:06:51.200 回答