Reputation: 131
I am needing away to insert data to a database based on an auto generated list from a form.
So I have this that lists out the key and value, but I need to create an array that I can then use a $sql insert to database.
foreach ($_POST as $key => $value) {
if($value != "") {
print $key.": ".$value . "<br>";
}
}
So then I have this for $sql insert
$sql = "INSERT INTO FDPU ($key) VALUES ('$value')";
if ($conn->query($sql) === TRUE) {
echo $key.'='.$value.'New record created successfully'.'<br />';
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
Upvotes: 0
Views: 92
Reputation: 8577
Not tested, but something like this should do it:
$keys = array();
$values = array();
foreach ($_POST as $key => $value) {
if($value != "") {
$keys[] = $key;
$values[] = "'" . $value . "'";
}
}
$sql = "INSERT INTO FDPU (" . implode(',', $keys) . ") VALUES (" . implode(',', $values) . ")";
It stores the keys and values of the variables that are not empty, and then put them together using the very handy function implode.
Upvotes: 1