3

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')");
2
  • 6
    You really don't want to do this. Look at stackoverflow.com/search?q=parameterized+sql instead. Commented Jul 31, 2012 at 15:55
  • 1
    I'd read up on SQL injection attacks and how to prevent them. This can work - but you need to make sure you are defending against these things as they are very easy to do for an attacker - and what Nate said - parameterized queries Commented Jul 31, 2012 at 15:56

3 Answers 3

10

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Ahhh.. silly me. Cant believe i did not notice the FROM word myself. Thank you!
0

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')");

2 Comments

message_id, even if it's the PK, isn't necessarily an autoincrement!
re: auto-increment, with mysql4 an empty string was (incorrectly) permissable. The advent of PHP5 caused this behaviour to stop, so you should either do as J A says or use an integer 0 (unquoted), if it is indeed an auto-increment of course. Caught me out when I upgraded.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.