1

我正在使用类似的语法

$query  = "SELECT * FROM contacts WHERE contact_id = $id";

它通常有效,但通常无效。那么如果我使用

$query  = 'SELECT * FROM contacts WHERE contact_id = "'.$id.'";

然后它工作。哪一个是正确的方法?

4

2 回答 2

3

In fact, neither of these syntaxes is best, when it comes to writing a SQL query.

If you're writing a SQL query, you are far better off writing it using parameterised queries, like so:

$query = 'SELECT * FROM contacts WHERE contact_id = ?';
$prep = $mysqli->prepare($query);  //prepares the query for action
$prep->bind_param("i", $id);       //inserts the $id variable into the '?' as an integer value.

...or similar methods using the PDO library.

Doing queries this way will make your queries more secure.

Please note that if you're using the old style mysql_xx() functions (which do not support this style of code), these are considered obsolete and insecure, and will be removed from a future version of PHP. You should stop using them as soon as possible. (see the PHP manual for more info on this)

It wasn't clear from the question whether you were asking about string syntax or query writing style. The above helps with query writing, and also avoid the issue with string syntax, but in case you still want to know about the string syntax issues, I will continue with some thoughts on that topic too....

Both syntaxes are perfectly valid. The short answer is that it's fine either way, so do it whichever way works best for you in any given bit of code.

You mentioned that your first syntax "often does not work". It would be helpful if you could elaborate on that, because it is perfectly valid PHP syntax.

Reasons it may fail are if you have other words joining onto variable names so PHP, or if you are trying to use an array element as the variable. In this case, you should wrap your variable names in braces like so:

$string = "this is a string with a {$variable} in it";

In fact, this works in all cases (and also helps make it clearer when you're using a variable in a string), so is best to do it all the time.

Some people will say that using single quotes is better for performance. It is.... but the difference is very marginal, and in fact, when you're concatenating a lot of variables it becomes even less. To be honest, if they're that worried about performance that this kind of thing is an issue for them then they shouldn't be using an interpreted language like PHP.

于 2012-10-21T11:06:31.953 回答
1
$query  = "SELECT * FROM contacts WHERE contact_id = '". $id . "'";

但查询很容易受到SQL Injection. 这是一篇如何保护您的代码的文章SQL Injection

在 PHP 中防止 SQL 注入的最佳方法是什么?

如果您要过滤的列不是数字,则下面的查询将不起作用。

$query  = "SELECT * FROM tableName WHERE username = $name";
于 2012-10-21T10:41:43.200 回答