I have a dynamic HTML form with three fields (item, number, cost). Users can add as many rows as they need. Because of this, I have set the fields names as item[], number[], cost[] in order to loop through the post and insert the values in the DB.
I have verified that the values are posted correctly up correctly through vardump, and I have checked that the following loop is picking up the values (both key and value) through printr. (and also simply echoing $value1).
foreach ($_POST as $field => $value) {
foreach($value as $field1 => $value1){
echo $field . ':' . $value1 . '</br>' ;
}
};
However, if I try insert passing the values to execute, nothing happens (no data is inserted and I get no error message).
if($_POST['submit']){
try {
$pdo->beginTransaction();
$stmt = $pdo->prepare('INSERT INTO invoice (item, number, cost) VALUES (?,?,?);');
foreach ($_POST as $item => $value) {
foreach($value as $item1 => $value1){
$stmt->execute($value1);
}
}
$pdo->commit();
}
catch (Exception $e){
$pdo->rollback();
throw $e;
}
}
I know that $value1 holds the correct values, but they are not being inserted. Can anyone help?
I have tried:
https://phpdelusions.net/pdo_examples/insert#multiple
PDO insert statement with loop through $_POST array
PDO insert array values Insert multiple rows using form and PDO
Need php pdo implode arrays and insert multiple rows in mysql
As your $_POST array contains columns you need to get values from the corresponding cells, i.e. for the first row you need items[0], number[0] and cell[0] and so on. So iterate over the first column, get the index and use that index for the other two
foreach ($_POST['item'] as $i => $item) {
$stmt->execute([$item, $_POST['number'][$i], $_POST['cost'][$i]]);
}
Related
I have an array of data that I would like to insert into my SQL database (table), I then want to be able to fetch it as an array in a separate file. I have no idea how to put it in as an array and get it back out as an array
This is for a contract, I have already tried inserting it as a string and then getting it out as an array but that doesn't work
$added = $_POST['added']; // this is the array
foreach ($added as $addedArr){
}
and I tried inserting $addedArr
That's the only code i can really show, I'm very stuck.
Using PDO (guide), for example, you could execute a query with an array, giving you a few options.
One such option would be to execute numerous queries with each sub-array, such as:
foreach ($arrays as $array) {
$query = $database->prepare('SELECT name, color, calories FROM fruit WHERE calories < ? AND color = ?');
$query->execute($array);
}
Another option would be to flatten out your array and do a multi line query like so:
$flat_array = []; //The array that will contain all the values of the main array of data
$query = 'insert into fruit (name, color, calories) values '; //Build the base query
foreach ($arrays as $array) {
$query .= '(?, ?, ?),'; //Add in binding points to the query
foreach ($array as $value) $flat_array[] = $value; //Add each value of each sub-array to to the top level of the new array
}
$query = $database->prepare(substr($query, 0, -1)); //Prepare the query, after removing the last comma
$query->execute($flat_array); //Execute the query with the new, flat array of values
You would then be able to pull out the data into an associative array later on with that same guide.
I have this sql statement that gets user input from a form and stores the values in the database
foreach ($_POST["name"] as $key => $name) {
$sql = "INSERT INTO test_table(name,price) VALUES ('".$name."','".$_POST["price"]."')";
$mysqli->query($sql);
}
In my database, I get the correct name value but on the price field I get an array. Is there a way to get the value of the POST['price']?
you need to loop through the price too
If you are getting values from a single form do you need to pass them individually
you can create an array like this
$form_field = array($_POST["name"], $_POST["price"]);
foreach($form_field as $field => $value){
$sql = "INSERT INTO test_table(name,price) VALUES ('".$value[0]."','".$value[1]."')";
$mysqli->query($sql);
}
Try this out and see
I'm new to PHP and I'm trying to insert data from a nested array into a database. I'm noticing though that only the last key:value gets put in (seems almost as if everything else before gets overwritten). How do I get a new line of each data so everything gets put in?
$tmpArray = array(array("one" => abc, "two" => def), array("one" => ghi, "two" => jkl));
// Scan through outer loop
foreach ($tmpArray as $innerArray) {
// Scan through inner loop
foreach ($innerArray as $key => $value) {
if ($key === 'one') {
$sql = "INSERT INTO test2 (alpha, beta) VALUES ('$key', '$value')";
}
}
}
For simplicty, all I'm trying to do is to get "one" and "abc" put into alpha and beta. Then have another row of the table input "one" and "ghi". But when I run the code, all I get is "one" and "ghi". When I put an echo statement though, all the correct stuff gets printed. Just don't understand why they aren't getting input into my tables.
What am I doing wrong? Thanks!
$sql = "INSERT INTO test2 (alpha, beta) VALUES ('$key', '$value')";
This line overwrites the contents of the variable $sql every time it is called. You need to concatenate your strings together instead:
$sql = '';
// Scan through outer loop
foreach ($tmpArray as $innerArray) {
// Scan through inner loop
foreach ($innerArray as $key => $value) {
if ($key === 'one') {
$sql .= "INSERT INTO test2 (alpha, beta) VALUES ('$key', '$value'); ";
}
}
}
Still better, as suggested in a comment, would be to simply execute the query directly rather than store it in a variable. Then you don't have to concatenate the strings together, nor do you have to enable multiple statements in a single MSQLI call.
I have a table that was dynamically created using jquery. Now I am sending the inputs, that are array, of course, to a database. The fields are customCLASSE[], customQTY[], customPRICE[]... and this is my script that inserts the data within MySQL:
if ($_POST['customCLASSE']) {
foreach ( $_POST['customCLASSE'] as $key=>$value ) {
$query = $mysqli->query("INSERT INTO booking_multiday_detail (classe) VALUES ('$value')");
}
}
It is working very good but my question is: How do I insert the other inputs (customQTY[], customPRICE[]...) within the same foreach in the same time that customCLASSE is being inserted?
$key is the index of array on looping cycle.
So if your other arrays sorted as well as customCLASSE you can access other arrays' value by $key like this,
if ($_POST['customCLASSE']) {
foreach ( $_POST['customCLASSE'] as $key=>$value ) {
$customQty = $_POST['customQTY'][$key];
$customPRICE= $_POST['customQTY'][$key];
//change the query
//....
$query = $mysqli->query("INSERT INTO booking_multiday_detail (classe) VALUES ('$value')");
}
}
This is a snippet of my code. I essentially I have a new array I want to insert into tablename, but before I do that I validate the new stat figures against the old ones, confirm they are numeric and insert into a new row.
I realise what I have done, the mysql_query is inside the foreach loop, it inserts 5 rows all the same. I want it to only insert 1 new row.
How Do I take the mysql_query outside the loop yet keep the validation that the foreach loop provides before attempting to insert a new row?
foreach ($statnumber as $element) {
if ($statnumber != $LastWeeksStats && is_numeric($element)) {
mysql_query("INSERT INTO tablename (idproducts, stat1, stat2, stat3, stat4, stat5, superstat1) VALUES('8', '$statnumber[0]', '$statnumber[1]', '$statnumber[2]', '$statnumber[3]', '$statnumber[4]', '$statnumber[5]')") or die(mysql_error());
} else {
echo "'{$element}' is NOT numeric or results same as last week", PHP_EOL;
}}
mysql_close();
I would remove the elements that fail the check from the array then have the mysql statement outside the loop at the end. Use unset but you have to keep track of what keys to unset like this:
foreach ($statnumber as $key => $element) {
if($statnumber != $LastWeeksStats && is_numeric($element)) {
//do nothing because it is valid
} else {
//remove that element from the array
unset($statnumber[$key]);
echo "'{$element}' is NOT numeric or results same as last week", PHP_EOL;
}
}
//now only valid data is in the array and you can use a mysql query
You will have to update the mysql query based on how many elements are actually in the array at the end like so:
foreach($statnumber as $key => $element) {
$keys[] = "stat$key";
$elements[] = "'$element'";
}
$keystring = implode(",",$keys);
$elementstring = implode(",",$elements);
mysql_query("INSERT INTO tablename (idproducts, $keystring, superstat1) VALUES('8', $elementstring)") or die(mysql_error());