我有一个数据库表。我想创建一个文本输入,用户可以在其中输入“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
提前感谢您的帮助!
答案 0 :(得分: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";
出于安全原因,建议转义变量中的字符。看看这个文档有一些原因:
答案 1 :(得分:3)
要从SQL注入攻击中保存,请使用:
$search_query = mysql_real_escape_string($_POST['blahblah']);
$query = "SELECT name, age FROM people WHERE uid = '".$search_query."' LIMIT 0 , 1";
答案 2 :(得分: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";
答案 3 :(得分: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']) );