开发者

PHP - Single quotes or double quotes around SQL query?

Is there any differences in using single quotes vs. using double quotes around a whole SQL query?

Which is better:

This approach (with single quotes):

    $username = mysql_real_escape_string($username);
    $password = mysql_real_escape_string($password);

    $sql = 'SELECT * FROM users WHERE username = "' . $username . '" AND password = "' . $password . '" LIMIT 1';

?

Or this approach (using double quotes):

    $username = mysql_real_escape_string($username);
    $password = mysql_real_escape_string($password);

    $sql = "SELECT * FROM users WHERE username = '{$username}' AND password = '{$password}' LIMIT 1";

Is there a better way to accomplish this?

For me I like the first approach as I always prefer single quotes in PHP. So I want to make sure that using single quotes around a whole SQL query is OK and using double quotes around variables or 开发者_如何学Pythondata is OK and is cross-platform and could be used with databases other than MySQL!


Use PDO instead of either of these approaches. It will allow you to use parameters instead of strings.

$sth = $dbh->prepare('SELECT * FROM users WHERE username = :username AND password = :password LIMIT 1');
$sth->bindParam(':username', $username, PDO::PARAM_STR);
$sth->bindParam(':password', $password, PDO::PARAM_STR);
$sth->execute();

By the way, make sure that you're not using passwords in plain text at the same time.


They are both equally horrid. :) Forget that you ever heard of mysql_real_escape_string and use PDO as acrosman mentioned. Specifically look at the prepare statement: http://www.php.net/manual/en/pdo.prepare.php. This is especially important as you even say: "is cross-platform and could be used with databases other than MySQL!" Not trying to come off as a jerk, but hint: code that calls to methods that start with mysql_ is probabl not that cross-platform ;). Using PDO however, will allow you to use databases other than Mysql. Of course, the obvious caveat here of different flavors of sql, but at least you don't have different flavors of what strings need to be escaped if you use parameterized queries.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜