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')");
}
}
Related
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]]);
}
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 gonna try to be as clear as possible.
I'm currently working on a project for my work, with dynamic forms where the form inputs are in a database, and created dynamically. Every input row looks something like:
Question? Radiogroup Textinput
And when the user press submit in a section of maybe 3-5 of these rows the form is serialised and managed with AJAX. So here comes the part I'm having trouble with, as of now, in my AJAX file, there is a foreach loop which loops through all $_POST values, adds them to an array and then after the array is complete all data is inserted to a SQL database. And I don't know if it's a problem since I'm not a professional DBA, but there's a lot of rows being inserted to the database, since EVERY radio group, and EVERY text input, gets their own row. And I was thinking if I at least could cut it down to every question getting their own row, but how do I then merge the radio group value with the text input value so they are on the same row but different columns.
I hope I'm being clear enough here.
Database layout today
|ID|RowID|Type|User|Value
Where Type is either Radio or Text. What I want to achieve to get half of the rows I'm gonna get this way is:
|ID|RowID|Type|User|Radio|Text
And the problem is howto achieve this when my foreach loop fills an array with a lot of rows, for each form, which as I say, is containing maybe 3-5 rows with both a radio group and a text input. This is how I do it today:
foreach($_POST as $key => $value) {
$values[] = "'{$id}', '{$user}', '{$type}', '{$value}'";
}
$mysqli->query('INSERT INTO data (rowid, user, type, value) VALUES ('.implode('),(', $values).')');
Hope someone can help me out.
Best Regards
Cisco
Solved it by doing the following:
//Only define for testing.
$_POST['rad_1'] = "yes";
$_POST['rad_2'] = "no";
$_POST['rad_3'] = "yes";
$_POST['txt_1'] = "Test";
$_POST['txt_2'] = "Test2";
$_POST['txt_3'] = "Test3";
$array = array();
foreach($_POST as $key => $value) {
$keyarr = explode('_', $key);
$type = $keyarr[0];
$id = $keyarr[1];
$value = $value;
$array[$id][$type] = $value;
}
$values = array();
foreach($array as $key => $value)
{
$values[] = implode(', ', $value);
}
$query = "INSERT INTO table_name test VALUES (" . implode ("),(", $values) . ")";
I'm trying to load a multi numbers(rows) to a database from a form. Anyone can help with the code?
$n = $_POST['txtname'];
foreach ($a as $value) {
$sql = "INSERT INTO Sheet1 VALUES($value)";
You need to initialise an array with the data before using the foreach loop.
You should use the following format:
//Obtain values from form text boxes
$name = $_POST['Name'] //This must match the name input on your form
//Populate values into array
$arrayData = array('$name'); //Can also populate with multiple values..
//Query
foreach ($arrayData as $value) {
$sql = "INSERT into table_name (table_column_name) VALUES($value)";
}
Sources: http://www.w3schools.com/sql/sql_insert.asp
http://bbrown.kennesaw.edu/papers/php2.html
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());