简体   繁体   English

在SQL中使用PHP变量

[英]Using PHP variables in SQL

I am trying to use PHP variables in an INSERT SQL statement. 我正在尝试在INSERT SQL语句中使用PHP变量。 Ive seen previous answers to this but can not get mine to work. 我已经看过以前的答案,但是无法让我工作。 Here is the code.. 这是代码。

mysql_query("INSERT INTO message (message_id, from, content) values ('', " . $uid . ", 'test message content')");

The main problem is that from is a reserved word and should be in backticks. 主要问题是from保留字 ,应该放在反引号中。

mysql_query("INSERT INTO message (message_id, `from`, content) VALUES ...");

But I'd also advise you to stop using the deprecated mysql_* functions. 但我也建议您停止使用不推荐使用的mysql_*函数。 I'd recommend that you take a look at PDO and prepared statements with parameters. 我建议您看一下PDO和带参数的预备语句。

如果message_id是主键,则除非有值,否则无需在查询中包括它。

mysql_query("INSERT INTO message (`from`, `content`) values (" . $uid . ", 'test message content')");

There are at least three issues in your query. 您的查询中至少有三个问题。 Two of them are syntax errors and one is a huge vulnerability. 其中两个是语法错误,一个是巨大的漏洞。

To make the query work, you should write it as follows: 为了使查询正常工作,您应该编写如下:

mysql_query("INSERT INTO message (message_id, `from`, content) values ('', '" . $uid . "', 'test message content')");`

Here's a summary of the errors: 以下是错误的摘要:
- As another user indicated, "from" is a keyword and you should not use it to name table columns. -正如另一个用户指出的那样,“ from”是关键字,您不应使用它来命名表列。 If you really want to use such name, you must use backticks to indicate it in the query. 如果您确实要使用这样的名称,则必须使用反引号在查询中进行指示。
- The value of $uid should be enclosed by single quotes. -$ uid的值应用单引号引起来。
- The third, and most important error, is that your query is vulnerable to SQL Injection . -第三个也是最重要的错误是您的查询容易受到SQL Injection的攻击。 You should use prepared statements, which would protect you from such attacks. 您应该使用准备好的语句,这样可以保护您免受此类攻击。

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

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