-2

Am trying to use dynamic column name in php mysql update but am getting error Here is code

 $time=date("H");
 $video_view = 234
 $update_query = "UPDATE videos SET ".  $time . "= {$video_view} WHERE id={$id}";

Here is the error

 UPDATE videos SET 14= 200079 WHERE id=1Query failedYou have an error in  
  your SQL syntax; check the manual that corresponds to your MariaDB  
 server version for the right syntax to use near '14= 200079 WHERE id=1' at line 1
ashwini
  • 1
  • 1

1 Answers1

1

First of all you should really use prepared statements and bound parameters.
If your column really got the name '14' like in the variable $time then you can try this

 $update_query = "UPDATE videos SET `".  $time . "` = {$video_view} WHERE id={$id}";

So far as I know column names should stand between `` because of reserved names like numbers or function names.
I would avoid it because it will make those errors und I don't know if the query does make sense

UfguFugullu
  • 2,107
  • 13
  • 18
  • please explain this. The question should get a proper answer – Funk Forty Niner Jun 01 '17 at 12:38
  • [Little Bobby](http://bobby-tables.com/) says ***[your script is at risk for SQL Injection Attacks.](http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php)***. Even [escaping the string](http://stackoverflow.com/questions/5741187/sql-injection-that-gets-around-mysql-real-escape-string) is not safe! – Jay Blanchard Jun 01 '17 at 16:28
  • 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 Jun 01 '17 at 16:29