简体   繁体   English

MySQL的PHP​​变数(SET'$ field'='$ value')

[英]PHP variables with MySQL (SET '$field' = '$value')

I'm trying to use PHP variables in a MySQL query like this: 我试图在这样的MySQL查询中使用PHP变量:

$field = "name_of_field";
$value = "new_value";
$sql = "UPDATE table SET '$field' = '$value'";

It doesn't work. 没用 When I take out the $field var and just use the name of a field it works. 当我取出$ field var并仅使用它的字段名称时。

Remove the quotes around the column name. 删除列名称周围的引号。

$field = "name_of_field";
$value = "new_value";
$sql = "UPDATE table SET $field = '$value'";

or use backticks 或使用反引号

$field = "name_of_field";
$value = "new_value";
$sql = "UPDATE table SET `$field` = '$value'";

Using backticks around column names ( and/or tables ) ensures that you've not used a (mysql) reserved word as well as using spaces in between words. 在列名( 和/或表 )周围使用反引号可确保您未使用(mysql) 保留字 ,也未在字之间使用空格。 This practice is discouraged. 不鼓励这种做法。

For example: (here are a few examples of reserved words) - try not using those for tables and/or column names, should this happen to occur anytime in the future. 例如:(这里有一些保留字的示例)-尝试不要将它们用于表和/或列名,如果将来任何时候发生这种情况。

  • for 对于
  • to
  • as
  • desc 降序
  • is
  • etc .

For a list of reserved words, consult the following page on mysql.com : 有关保留字的列表,请访问mysql.com上的以下页面:

Example of spaces between words for tables and columns: (while using backticks) 表和列的单词之间的空格示例:(使用反引号时)

SELECT `column one` FROM `my table`

which would be valid. 这将是有效的。

Yet, by using the following 但是,通过使用以下

SELECT column one FROM my table

would produce an error. 会产生一个错误。

It's best to use underscores and not hyphens ( should this also be the case for future development ). 最好使用下划线而不是连字符( 如果将来的开发也是如此 )。 Using hyphens is discouraged to use as a word seperator, as SQL will misinterpret the hyphen as a minus sign, in thinking you want to do some form of mathematical problem. 不建议使用连字符作为单词分隔符,因为SQL会以为您想要做某种形式的数学问题,因此会将连字符误解为负号。


When in development: (use error reporting) 开发时:(使用错误报告)

error_reporting(E_ALL);
ini_set('display_errors', 1);

and the following if using mysqli_ functions: 如果使用mysqli_函数,则以下内容:

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

MySQL (error reporting links) MySQL(错误报告链接)

PDO PDO

您不会在字段名称周围使用单引号,而使用反引号`

Two things wrong. 两件事错了。

  1. Firstly, you need to wrap your value for $sql in quotes. 首先,您需要将$sql的值用引号引起来。
  2. You need to remove the single quotes around $field 您需要删除$field周围的单引号
  3. You can wrap $field in curly braces (optional) 您可以将$field用花括号括起来(可选)

Result: 结果:

$field = "name_of_field";
$value = "new_value";
$sql   = "UPDATE table SET `{$field}` = '$value'";

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

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