I am trying to insert a $_POST array into a mysql database. The foreach works but not all values are inserted on the same row as you can see on the image below.
This is the foreach that i use to insert the array into the database:
if($_POST)
{
// con->insert is my mysql function to insert the values
foreach ($_POST as $key => $value) {
if($con->insert('test',$key, $value)==true)
{
echo 'Het werkt!!!';
}
}
}
EDIT This is the con function
public function insert($table,$row,$value) {
$query = mysqli_query($this->connect, "INSERT INTO `$table` (`$row`) VALUES ('$value')");
if ($query == true)
{
return true;
}
else{
return false;
}
}
I want to collect the variables from the post and then i want to put them in the database on the same row of the table.
How can i get the values on the same row? Thank in advance
The values get into different rows because you are doing one insert per variable.
You probably want to collect all variables from the $_POST and add them to the database in a single insert.
Firstly, change your insert clause like this:
public function insert_multi($table, $items) {
$query = mysqli_query($this->connect,
"INSERT INTO `$table` (`firstKeyName`, `secondKeyName`) ".
"VALUES ('".$items['firstKeyName']."', '".$items['secondKeyName']."')");
if ($query == true)
{
return true;
}
else{
return false;
}
}
Then call it only once with all params:
$con->insert_multi('test', $_POST);
Ultimately, you are doing one insert command for every value, when you should be doing one for every key and value pair.
One option you can try is to insert the $_POST array as JSON data.
<?php
$db = mysqli_connect(...);
foreach($_POST as $key => $value) {
mysqli_query($db, "INSERT into `table` VALUES ($key, $value)");
}
INSERT INTO
$table
($row
) VALUES ('$value')
Normally (if this is not phpMySqlAdmin that you are writing), your application knows what columns are available for a given table, and you totally need to validate the values for $row, otherwise it is a terrible potential for SQL injection.
And if you have a list of column names, you can do
INSERT INTO test (Col1, Col2, Col3) VALUES (?, ?, ?)
and you can give it the array
$_POST["COL1"], $_POST["COL2"], $_POST["COL3"]