1

I am getting a string using PHP and then trying to put it into my database(mySql). I keep getting an error

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'material )' at line 1.

Here is my code. I printed out the statement in php and that is correct.

$description=$_POST["textField4"];

$description= addslashes($description);//found these two line using google
$description = mysql_real_escape_string($description);//neither seem to help.


$sql="INSERT INTO budget8000 (categories,subCategory, amount, date, description)
VALUES ($category,$subCategory, $amount, curdate(), $description )";
sdleihssirhc
  • 42,000
  • 6
  • 53
  • 67
Aaron
  • 4,380
  • 19
  • 85
  • 141

2 Answers2

2

The proper way to do this is:

$description=mysql_real_escape_string($_POST["textField4"]);
...
//and so on for each an every field that you $_GET or $_POST.

$sql= "INSERT INTO budget8000 (categories,subCategory, amount, date, description)
VALUES ('$category','$subCategory', '$amount', curdate(), '$description' )";
//      ^         ^ these quotes are vital to prevent SQL-injection and errors.
// without them mysql_real_escape_string will not work!

See: How does the SQL injection from the "Bobby Tables" XKCD comic work?

Community
  • 1
  • 1
Johan
  • 74,508
  • 24
  • 191
  • 319
  • As a matter of fact, it's part of SQL syntax. So, these quotes vital to prevent syntax errors, not injections. – Your Common Sense Aug 28 '11 at 20:55
  • @Col, welcome back; as always you are correct, But I find it easier to remember that it is to prevent SQL-injection AND errors, because without the quotes the code **may** work, but you can be 100% sure that you are at risk of SQL-injection pwn-age. – Johan Aug 28 '11 at 20:57
-1

You need to use the php function mysql_real_escape_string()

$description = mysql_real_escape_string($description);

PHP documention for mysql_real_escape_string

Mindfulgeek
  • 141
  • 4
  • the OP has already done, that. But using mres is not enough, you need to ALSO quote all the injected vars. – Johan Aug 28 '11 at 20:53
  • I didn't downvote, but that's exactly why. You did not answer the question, the OP already uses mysql_real_escape_string (incorrectly, but that's beside the point), and the error is not caused by mres. It is caused by not quoting the injected vars. – Johan Aug 29 '11 at 07:15