好的,所以你正在使用PDO
,很好。但是,您的代码段仍然容易受到注入攻击:您仍在将原始用户输入传递给查询。SELECT *
此外,如果您想要的只是找到的行数,请不要使用,并且不要获取完整的结果集来计算它们!
function uni($field,$value)
{
$db = new PDO();//make connection, which you don't seem to do
//or (not so good approach):
//global $db;
//Best approach would be to pass the connection to the function, as an extra argument, though
$stmt = $db->prepare('SELECT '.$field.' FROM user WHERE '.$field.' = :value');
if ($stmt->execute(array(':value' => $value)))
{
return $stmt->rowCount();
}
//query failed, throw errors or something
}
阅读文档以获取更多示例。
无论如何,您的代码应该如下所示:
function uni($field,$value,$db)
{
$stmt = $db->prepare('SELECT '.$field.' FROM user WHERE '.$field.' = :value');
if ($stmt->execute(array(':value' => $value)))
{
return $stmt->rowCount();
}
return false;
}
$username = $_POST['username'];
$result = uni('username', $username,$pdo);//<--pass connection