You are not executing your query -
$sql="INSERT INTO roller
('$col') VALUES ('$_POST[name]') ";
Also, since you are using PDO
, you should use prepared statements to prevent SQL Injection.
Since columns cannot be used in a prepared statement, you will need to whitelist it. see Reference - frequently asked questions about PDO
$query = $pdo->prepare("INSERT INTO roller (`$col`) VALUES (?) ");
$query->execute(array($_POST['name']));
edit
if you want to insert $_POST["name"]
into each table column ($_POST["categories"]
), you could do something like this -
<?php
$pdo= new PDO('mysql:host=localhost;dbname=ronre', 'roon', 'abc12345');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->exec('SET NAMES "utf8"');
$tbl_cols = array("col1","col2","col3", ...); // column names in roller table.
if (is_array($_POST["categories"])){ // check if array
foreach ($_POST["categories"] as $col){ // loop through each $_POST["categories"]
if(in_array($col,$tbl_cols)){ // make sure it is safe by whitelisting it
$query = $pdo->prepare("INSERT INTO roller (`$col`) VALUES (?) ");
$query->execute(array($_POST['name']));
}
}
}
exit();
?>
or if you want to do it in one query, rather then in a loop, try something like -
<?php
$pdo= new PDO('mysql:host=localhost;dbname=ronre', 'roon', 'abc12345');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->exec('SET NAMES "utf8"');
$tbl_cols = array("col1","col2","col3", ...); // column names in roller table.
if (is_array($_POST["categories"])){ // check if array
foreach ($_POST["categories"] as $col){ // loop through each $_POST["categories"]
if(in_array($col,$tbl_cols)){ // make sure it is safe by whitelisting it
$cols[]=$col; // create an array of safe column names
}
}
}
$name = array_fill(0, count($cols), $_POST['name']); // create an array of $_POST['name'] with same amount as $cols
$num_of_vals = str_repeat('?,', count($cols) - 1) . '?'; // create n number of ? same as $cols / $name
$cols = implode("`, `", $cols); // implode the $cols to get a csv of $cols
$query = $pdo->prepare("INSERT INTO roller (`$cols`) VALUES ($num_of_vals) ");
$query->execute(array($name));
exit();
?>