-4

I looked for my problem in the archive but the solutions reported were not good for my case. I can not understand the right syntax to insert a php variable instead of the table name:

$insert_sql = "INSERT INTO galleria1(contatore, immagine) VALUES ('', '".$filename."')";

where instead of galleria1 I have to enter the $gallery php variable. Thanks to those who can help me.

2 Answers2

0

Simply do like following:

$insert_sql = "INSERT INTO `" . $gallery . "`(contatore, immagine) VALUES ('', '".$filename."')";

And make sure that $gallery variable has the value in it actually. So for debugging you can simply echo $insert_sql; to check if sql is in right syntax.

Important Note

Above code is very not safe regarding SQL Injection, so please check following article:

How can I prevent SQL injection in PHP?

,to learn how to handle the case.

Codemole
  • 3,069
  • 5
  • 25
  • 41
  • 2
    Turn the tide against teaching/propagating sloppy and dangerous coding practices. If you post an answer without prepared statements [you may want to consider this before posting](http://meta.stackoverflow.com/q/344703/). Additionally [a more valuable answer comes from showing the OP the right method](https://meta.stackoverflow.com/a/290789/1011527). – Jay Blanchard Dec 15 '17 at 16:53
0

With this syntax:

$insert_sql = "INSERT INTO " . $gallery . "(contatore, immagine) VALUES ('', '".$filename."')";

I have this error message:

database error: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '(contatore, immagine) VALUES ('', '03.jpg')' at line 1

If I change $galleria with the name of table in database (galleria1) the code is ok.

  • Check my answer as I made some revision. From the error message, I feel that $gallery is empty variable without any value. You can simply echo the $insert_sql first, to see if it is in correct way. – Codemole Dec 15 '17 at 17:17
  • Thanks, I was wrong, instead of writing $galleria, I had written $galleria1 that did not exist. $galleria has a value inside it and now it works. – Stefano Forcina Dec 15 '17 at 17:24
  • you are welcome. you can accept my answer above then. :D – Codemole Dec 15 '17 at 17:39