简体   繁体   English

mysqli_query的'单引号和'反引号之间的区别

[英]difference between ' single quote and ` backtick for mysqli_query

This is bizarre, I'm changing some code from mysql to mysqli functions cause of php 5.5+, in these two basic examples, mysql_query had no ' single quote nor ` backtick and worked fine. 这很奇怪,我正在将一些代码从mysql改为mysqli函数导致php 5.5+,在这两个基本的例子中,mysql_query没有'单引号也没有'反引号并且运行正常。

$sql = "SELECT * FROM `".$table."`"; // requires: ` ` or fails
$result = mysqli_query($con,$sql);

$sql = "SHOW TABLES LIKE '".$table."'"; // requires: ' ' or fails
$result = mysqli_query($con,$sql);

Can someone explain why? 有人可以解释原因吗?

EDIT: I guess the essence of my question is that: Both functions worked fine without any kind of quotes with mysql_query , and both failed mysqli_query without some kind of quotes. 编辑:我想我的问题的本质是:两个函数都运行正常,没有任何类型的引用与mysql_query ,并且两个函数都没有引用mysqli_query失败。 Meaning I will have to fiddle around with half my query's when changing from mysql_ to mysqli_ 这意味着当我从mysql_更改为mysqli_时,我将不得不摆弄一半的查询

In your first select statement you are trying to select a table by it's name, hence it will accept the name either with ` or without them, but now with single or double quotes. 在您的第一个选择语句中,您试图按名称选择一个表,因此它将使用`或不使用它们来接受名称,但现在使用单引号或双引号。 These should work : 这些应该工作:

 $sql = "SELECT * FROM `table_name`";
 $sql = "SELECT * FROM table_name";

In the second case you need to pass in a string to be compared by the like statement hence you need to surround it either with single ' or double " quotes: 在第二种情况下,你需要在一个字符串传递给由被比较like的语句,因此你需要或者单将其包围'或双"引号:

$sql = "SHOW TABLES LIKE 'string'";
$sql = "SHOW TABLES LIKE \"string\"";

Edit: 编辑:

Check out this previous answer on SO as well: Using backticks around field names 在SO上查看之前的答案: 在字段名称周围使用反引号

Edit 2: 编辑2:

Since we (me and in comments) suggested that backticks are somehow optional, keep in mind that as a best practise use them whenever you can since although it will allow you to pass most queries without them, some queries using MySql reserved words would break when containing mysql reserved words 由于我们(我和评论中)建议反引号在某种程度上是可选的,请记住,作为最佳实践,尽可能使用它们,因为虽然它允许您在没有它们的情况下传递大多数查询,但使用MySql保留字的某些查询会在包含mysql保留字

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM