何时使用 PDO 准备查询.mysql_real_escape 错误 [英] When to use PDO prepared queries. mysql_real_escape error

查看:32
本文介绍了何时使用 PDO 准备查询.mysql_real_escape 错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作一个 php 网站,在我的本地机器上开发.对此真的很陌生,所以这是我尝试过的第一件事.当我搬到我的主机时,我收到以下错误:

I'm been making a php site, developing on my local machine. Really new to this so this is the first thing i've ever attempted. When I moved to my host, i get the following error:

 Warning: mysql_real_escape_string() [function.mysql-real-escape-string]: Access denied             for user 'matthew'@'localhost' (using password: NO)  on line 11

我在这里搜索了很多,我很确定这是因为我需要准备"我的查询.我不确定什么时候准备正确,什么时候不正确.我在下面添加了一些查询以进行详细解释:

I've searched on here a fair bit and I'm pretty sure its because i need to 'prepare' my queries. What I am unsure of is when is it correct to prepare, and when not. I've added some of my queries below to explain in detail:

连接到数据库:

$hostname = "localhost";
$username = "root";
$password = "root";

try {
    $dbh = new PDO("mysql:host=$hostname;dbname=wmpt", $username, $password);
//echo "Connected to database"; // check for connection
    }
catch(PDOException $e)
    {
    echo $e->getMessage();
    }

这是一个示例查询:

$username = mysql_real_escape_string($_POST['run']);


$STH = $dbh->query("SELECT * FROM tblusers WHERE username = '$username' ");
$STH->setFetchMode(PDO::FETCH_ASSOC);  
$result = $STH->fetch();

我的问题是,如果我使用用户提交的数据查询/插入/更新数据库,我是否只需要准备"一个查询?

My question is, do I only need to "prepare" a query if I am querying/inserting/updating the DB with user submitted data?

上面的查询是不好的做法吗?如果它不包含用户提交的数据怎么办,即我想查询

Is the above query bad practice? What if it didnt contain user submitted data, ie i wanted to query

 $STH = $dbh->query("SELECT * FROM tblusers WHERE username LIKE '%hotmail%' ");

这可能是一个不好的例子,但我正在说明一个开发人员定义的查询.

That probably a bad example, but I'm illustrating a developer defined query.

这是我得到的原因吗,我该如何避免:

Is this the reason I get, and how i can avoid:

Warning: mysql_real_escape_string() [function.mysql-real-escape-string]: Access denied for     user 'matthew'@'localhost' (using password: NO)  on line 11

推荐答案

如果您使用 PDO,则不应使用 mysql_real_escape_string.PDO 库有一个非常强大的 SQL 占位符方法 做得更好.

If you're using PDO, you should not be using mysql_real_escape_string. The PDO library has a very robust SQL placeholder method that does a much better job.

$STH = $dbh->query("SELECT * FROM tblusers WHERE username = :username");
$STH->bindParam(':username', $username);
$STH->setFetchMode(PDO::FETCH_ASSOC);  
$result = $STH->fetch();

这篇关于何时使用 PDO 准备查询.mysql_real_escape 错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆