PHP的-单引号或双引号围绕SQL查询? [英] PHP - Single quotes or double quotes around SQL query?

查看:167
本文介绍了PHP的-单引号或双引号围绕SQL查询?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在整个SQL查询中使用单引号和使用双引号有什么区别吗?

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

哪个更好:

这种方法(用单引号引起来):

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?

对我来说,我喜欢第一种方法,因为我一直更喜欢PHP中的单引号.因此,我想确保在整个SQL查询中使用单引号是可以的,并且在变量或数据周围使用双引号是可以的,并且可以跨平台使用,并且可以与MySQL以外的其他数据库一起使用!

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 data is OK and is cross-platform and could be used with databases other than MySQL!

推荐答案

使用 PDO 代替这些方法中的任何一种.它将允许您使用参数而不是字符串.

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.

这篇关于PHP的-单引号或双引号围绕SQL查询?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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