php – 如何在PDO中使用/编写mysql_real_escape_string?

前端之家收集整理的这篇文章主要介绍了php – 如何在PDO中使用/编写mysql_real_escape_string?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

参见英文答案 > 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();

我总是得到这个错误
在非对象上调用成员函数prepare()

最佳答案
关键是通过使用带参数化查询和绑定值的预准备语句,您不需要诸如@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);

任何类型的sql注入尝试,例如1′; DROP用户 – 在上面的变量中将不再起作用,因为它将按字面意思调用.

猜你在找的MySQL相关文章