0

Maybe a silly question, but I'm really struggling.

I've created a MySQL Database and Table and am trying to push data into it. The data in question is a unique ID and a load of Javascript.

Code is simple:

$sql = "INSERT INTO TableName (id, code)
VALUES ('$uniqueid', '$codeoutput')";

However, whilst I can get the ID in there, I can't get the DB to accept the Javascript (which is currently stored in the variable $codeoutput.

I get the error:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax

I'm not that familiar with using MySQL, and I have played around with different data types in PhpMyAdmin, but sadly still no luck.

What am I doing wrong? Do I need to have a very specific setup on the column where I'm storing the code? I'm currently trying to store it as medium text.

Is it something to do with needing to escape special characters? Is there an easy solution to this?

chris85
  • 23,846
  • 7
  • 34
  • 51
  • Can you include the actual code that is giving you the area, ie. the Javascript you are trying to insert into the table? You might not be escaping the data properly. Try inserting "TEST" to see if that works. – Bert Aug 31 '17 at 20:36
  • 4
    You have a syntax error in your SQL command. It seems fine to me (assuming you have correct table/column names), so maybe one of your PHP variable contains an apostrophe? Try using **prepared statements.** – juzraai Aug 31 '17 at 20:36
  • 5
    Tried using prepared statements/bind variables for the statement? http://php.net/manual/en/mysqli-stmt.bind-param.php or PDO https://phpdelusions.net/pdo#prepared – smcd Aug 31 '17 at 20:36
  • Well, I'm trying to put a load of Javascript into the database, so its full of apostrophes etc. Is there a way of getting the Database to accept code? –  Aug 31 '17 at 20:39
  • 4
    Yes, use parameterized queries. – chris85 Aug 31 '17 at 20:39
  • Can I use urlencode() and urldecode()? That way I could store the JS as a long string of data that shouldn't cause issues, and decode it at the other end when I query the database? –  Aug 31 '17 at 20:46
  • 1
    Just parameterize it is going to be much easier. – chris85 Aug 31 '17 at 20:49
  • Sorry to be dense, but how do you "parameterize it"? I've come across the concept before in terms of preventing SQL injection attacks, but in terms of writing my variable to the database, is there a simple way to do this? –  Aug 31 '17 at 20:55
  • 1
    You put a placeholder in place of every variable then bind the variables. `$sql = "INSERT INTO TableName (id, code) VALUES (?, ?)";` use that and the manual for whichever driver you are using and find . the proper binding syntax. – chris85 Aug 31 '17 at 20:58

1 Answers1

-6

simplest way to do it is

$sql = "INSERT INTO TableName ($uniqueid) VALUES ('id')";
$sql2 = "INSERT INTO TableName ($codeoutput) VALUES ('code')";
chris85
  • 23,846
  • 7
  • 34
  • 51