-3

So, I have this code that returns into a syntax error. Can you please help me figure out what the problem is?

$query = mysql_query("INSERT INTO tablename (column) 
VALUES('".$php_var."') WHERE cat = $php_var2") or die(mysql_error());
Matt
  • 14,906
  • 27
  • 99
  • 149
details
  • 23
  • 1
  • 4
  • you should provide more of your code. What is $php_var and $php_var2. What do you want as a result ? What is the table's structure ? – Unex Jun 12 '15 at 11:47
  • What error specifically? – Matt Jun 12 '15 at 11:48
  • $php_var is an integer and the column value is also an integer. The error says that is a sintax error near WHERE cat = $php_var2 – details Jun 12 '15 at 11:51
  • 1
    This has nothing to do with PHP - an `insert` statement just doesn't have a `where` clause. What exactly are you trying to achieve? – Mureinik Jun 12 '15 at 11:52
  • 1
    Please, read http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php – venca Jun 12 '15 at 11:53
  • you can only use a `where` clause in and INSERT when doing and [`INSERT ... ON DUPLICATE KEY UPDATE`](http://dev.mysql.com/doc/refman/5.6/en/insert-on-duplicate.html) – Funk Forty Niner Jun 12 '15 at 11:56
  • Your code is not only prone to SQL injection, it also uses deprecated methods. Please read http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php – Oldskool Jun 12 '15 at 12:00

3 Answers3

2

You cant use WHERE clause with INSERT. If you want to insert then the query will be -

"INSERT INTO tablename (column) VALUES('".$php_var."')"

Or if it is update then -

"UPDATE tablename SET column = '".$php_var."' WHERE cat = '" . $php_var2 . "'"

Try to avoid mysql. Use mysqli or PDO

Sougata Bose
  • 31,517
  • 8
  • 49
  • 87
  • b0s3 is correct. @details You are inserting a new row. are you want to update any data. – Bokul Jun 12 '15 at 11:54
  • 1
    ...or [`INSERT ... ON DUPLICATE KEY UPDATE`](http://dev.mysql.com/doc/refman/5.6/en/insert-on-duplicate.html) which does use a `where` clause. – Funk Forty Niner Jun 12 '15 at 11:59
0

You can't do INSERT with WHERE clause unless it's WHERE NOT EXISTS, so just do:

$query = mysql_query("INSERT INTO tablename (column) VALUES('$php_var')");

Maybe you needed to do UPDATE

$query = mysql_query("UPDATE tablename SET column='$php_var' WHERE cat = '$php_var2' ");
user3419778
  • 856
  • 3
  • 8
  • 11
0

INSERT INTO syntax can't accept a WHERE. The good syntax is:

INSERT INTO table_name 
VALUES(...);

Or, if you prefer not to insert in all the table columns:

INSERT INTO table_name(column_name1, column_name2, ...) 
VALUES(column1_value, column2_value, ...);

As a side note, in your request you don't insert your PHP variable, but some text.

Mistalis
  • 17,793
  • 13
  • 73
  • 97