Home:ALL Converter>php INSERT into column with variable name MySQL

php INSERT into column with variable name MySQL

Ask Time:2017-07-01T20:37:11         Author:Ola Karlsson

Json Formatter

Been looking around all over forums and found similarish issues like MySQL INSERT INTO with PHP $variable . But it's not quite getting to my question.

I want to use variables for the columns but I get errors with my MySQL insert statement

$columns = 'id, test';
$sql_store = "INSERT into test ('$columns') VALUES (NULL, 1)";
$sql = mysqli_query($db, $sql_store) or die(mysql_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 ''id, Storlek') VALUES (NULL, 1)' at line 1

Thankful for help!

Author:Ola Karlsson,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/44861030/php-insert-into-column-with-variable-name-mysql
Jaydeep Mor :

\n Problem : Your $columns variable is string which is not true.\n\n\nTry like this,\n\nPHP\n\n$columns_array = array('id','test');\n$columns = implode(\",\",$columns_array);\n$sql_store = \"INSERT into test (\".$columns.\") VALUES (NULL, 1)\";\n$sql = mysqli_query($db, $sql_store) or die(mysql_error());\n",
2017-07-01T12:40:29
yy