在我的代码中,我试图将 mysql_real_escape_string 转换为 PDO 语句。有人有关于如何在 PDO 中编写 mysql_real_escape_string 的提示吗?
我在两行中使用 mysql_real_escape_string: $userName = mysql_real_escape_string($_POST['username']); $password = sha1(mysql_real_escape_string($_POST['password']));
<?php
ob_start();
session_start();
include("../database/db.php");
$userName = mysql_real_escape_string($_POST['username']);
$password = sha1(mysql_real_escape_string($_POST['password']));
echo "<br>user: " . $userName;
echo "<br> pw: " . $password;
$query = "select * from tbladmin where admin_usr_name='$userName' and admin_pwd='$password'";
$res = mysql_query($query);
// $rows = $res->fetch(PDO::FETCH_ASSOC);
$rows = mysql_fetch_assoc($res);
echo "<br>numrows" . mysql_num_rows($res) . "<br>";
// $find = $query->prepare("select * from tbladmin where admin_usr_name='$userName' and admin_pwd='$password'");
// $find->execute();
// if ($find->fetchColumn() > 0)
// {
// echo 'You made it, welcome';
// $_SESSION['userName'] = $rows['admin_usr_name'];
// $_SESSION['admin_id'] = $rows['admin_id'];
// header("location: ../pages/content.php");
// }
// else
// {
// echo 'Username and password dont match <br/> Try again';
// header("location: ../index.php?loginerror=yes");
// }
if(mysql_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 <br/> Try again';
header("location: ../index.php?loginerror=yes");
}
?>
这就是我试图用 PDO 做的事情
$host = "localhost";
$user = "root";
$password = "root";
$db = "blog";
$dsn = "mysql: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, $user, $password);
}
catch (PDOException $e)
{
echo 'Connection failed: ' . $e->getMessage();
}
$statement = $databas->prepare($query);
$statement->execute(array(':userName'=>$username, ':passWord'=> $password));
$row = $statement->fetch();
我总是收到此错误:调用非对象上的成员函数 prepare()