简体   繁体   中英

Using PHP variables in SQL

I am trying to use PHP variables in an INSERT SQL statement. 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.

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

But I'd also advise you to stop using the deprecated mysql_* functions. I'd recommend that you take a look at PDO and prepared statements with parameters.

如果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. 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.
- The third, and most important error, is that your query is vulnerable to SQL Injection . You should use prepared statements, which would protect you from such attacks.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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