参见英文答案 > real escape string and PDO 3个
在我的代码中我试图将@R_403_198@_real_escape_string转换为PDO语句.有人有关于如何在PDO中编写@R_403_198@_real_escape_string的提示吗?
我在两行中使用@R_403_198@_real_escape_string:
$userName = @R_403_198@_real_escape_string($_ POST [‘username’]);
$password = sha1(@R_403_198@_real_escape_string($_ POST [‘password’]));
PHP
ob_start();
session_start();
include("../database/db.PHP");
$userName = @R_403_198@_real_escape_string($_POST['username']);
$password = sha1(@R_403_198@_real_escape_string($_POST['password']));
echo "
403_198@_query($query);
// $rows = $res->fetch(PDO::FETCH_ASSOC);
$rows = @R_403_198@_fetch_assoc($res);
echo "
403_198@_num_rows($res) . "
PHP");
// }
// else
// {
// echo 'Username and password dont match
PHP?loginerror=yes");
// }
if(@R_403_198@_num_rows($res)>0)
{
$_SESSION['userName'] = $rows['admin_usr_name'];
$_SESSION['admin_id'] = $rows['admin_id'];
header("location: ../pages/content.PHP");
}
else
{
echo 'Username and password dont match
PHP?loginerror=yes");
}
?>
这就是我试图用PDO做的事情
$host = "localhost";
$user = "root";
$password = "root";
$db = "blog";
$dsn = "@R_403_198@:host=$host;dbname=$db;charset=utf8";
$opt = array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC);
$pdo = new PDO($dsn,$user,$password,$opt);
$username = $_POST['username'];
$password = $_POST['password'];
$query = "select * from tbladmin where admin_usr_name=:userName and admin_pwd=:passWord";
try
{
$databas = new PDO($dsn,$password);
}
catch (PDOException $e)
{
echo 'Connection Failed: ' . $e->getMessage();
}
$statement = $databas->prepare($query);
$statement->execute(array(':userName'=>$username,':passWord'=> $password));
$row = $statement->fetch();
最佳答案
关键是通过使用带参数化查询和绑定值的预准备语句,您不需要诸如@R_403_198@_real_escape_string之类的东西.
查看PDO documentation有关如何使用绑定值和参数化查询/预准备语句的信息.
关键是你要编写一个SQL查询:
$query = $pdo->prepare("SELECT * FROM users WHERE username = ? and password = ?");
然后你会传入绑定值代替?符号,因此查询只是按字面意思运行:
$query->bindParam(1,$username);
$query->bindParam(2,$password);