Reputation:
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')");
Upvotes: 3
Views: 142
Reputation: 7572
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.
Upvotes: 0
Reputation: 1766
If message_id is primary key, you don't need to include it in the query unless you have a value..
mysql_query("INSERT INTO message (`from`, `content`) values (" . $uid . ", 'test message content')");
Upvotes: 0
Reputation: 839154
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.
Upvotes: 10