user887958
user887958

Reputation:

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

Upvotes: 3

Views: 142

Answers (3)

Diego
Diego

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

J A
J A

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

Mark Byers
Mark Byers

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

Related Questions