Loop through 3 arrays at once and save values in the database - php

I have three inputs type text in an HTML page and a button which if clicked duplicate each text box (Javascript) making them 6.
<input type="text" name="category[]">
<input type="text" name="quantity[]">
<input type="text" name="amount[]">
<button>Add more</button>
Which generate same inputs again:
<input type="text" name="category[]">
<input type="text" name="quantity[]">
<input type="text" name="amount[]">
A piece of code in Cakephp I have been trying:
$data = $this->request->data;
foreach($data['category'] as $index => $value){
$this->ModelName->save($value);
}
Trying to get two rows inserted at once with quantity, category and amount as columns. But it is not inserting and not giving any error.
Is there a way I can achieve this?
Thanks.

I'm not sure how your model works in cakephp, but you should be able to get a complete grouping of data like:
foreach($data['category'] as $index => $value){
$category = $value
$quantity = $data['quantity'][$index];
$amount = $data['amount'][$index];
// use the above 3 variables however you need to to persist the model
//$this->ModelName->save($value);
}
On a side note, you may want to consider reordering your html inputs to be like:
<input type="text" name="item[0][category]">
<input type="text" name="item[0][quantity]">
<input type="text" name="item[0][amount]">
And then maintain the next index, incrementing the numeric index of item for each additional group
This will allow you to iterate like:
foreach($data['item'] as $index => $group){
//$group['category'];
//$group['quantity'];
//$group['amount'];
}

Related

How to insert 2 inputs values simultaneously using HTML Arrays & PHP POST?

I am trying to pass 2 arrays in a MYSQL table using HTML array, I want to insert both values in the same row at the same time of the loop, of course nested loop isn't going to work, the first input value passed successfully, but the second input inserts wrong & unrelated values. I am sure it's because the for loop logic is incomplete, but I can't seem to adjust properly. any help will be appreciated.
HTML (...html code inside PHP then this, $row['id'] is the value that shall be passed to POST):
<input type="text" id="mytextbox" name="comment[]" placeholder = "Add your comments here" required>
<input type="text" id="mytextbox" list="decision[]" name="decision" placeholder = "Choose your decision" required>
<datalist id="decision[]">';
echo '<option value="'.htmlspecialchars($row['id']).'">'.htmlspecialchars($row['name']).'</option>';
<input type="text" id="mytextbox" name="comment[]" placeholder = "Add your comments here" required>
<input type="text" id="mytextbox" list="decision[]" name="decision" placeholder = "Choose your decision" required>
<datalist id="decision[]">';
echo '<option value="'.htmlspecialchars($row['id']).'">'.htmlspecialchars($row['name']).'</option>';
<input type="text" id="mytextbox" name="comment[]" placeholder = "Add your comments here" required>
<input type="text" id="mytextbox" list="decision[]" name="decision" placeholder = "Choose your decision" required>
<datalist id="decision[]">';
echo '<option value="'.htmlspecialchars($row['id']).'">'.htmlspecialchars($row['name']).'</option>';
PHP (after successful POST of $comment as input(1) & $decision as input(2) and working queries):
for ($i=0;$i<count($comment);$i++){
$query = "INSERT INTO table (otherid,col1,col2) VALUES ('$otherid','$comment[$i]','$decision[$i]')";
$result = $dbc->query($query);
}
You are getting only the last decision, because you did not use square brackets in the field name, as you did with the comments field. name="decision" needs to be name="decision[]". Only then will PHP create an array out of multiple passed parameters of the same name; without square brackets, they simply overwrite each other.
The duplicate IDs are only of client-side importance - selecting from those lists, will likely not populate the correct input field, but it has little to do with what actually gets submitted, if you filled those fields by hand. But you should be able to make thos IDs dynamic, for example by appending the row ID.
<datalist id="decision-123">, with a matching list="decision-123" on the input field.

How to insert form values, some with same name, to multiple MySQL rows

I have been searching this for the last couple of hours and there are a few very similar questions and answers but none are quite working for my situation. What I'm trying to do is insert a list of songs set to the same value for two columns, one per row, and with a couple of options set via radio buttons. The latter is the reason why I can't just write all of the songs in a textarea and split them.
This is what the form looks like (obviously not fully designed)
There are only three there now while I get it working, in reality an unlimited amount may be added via javascript.
And the code:
<form action="" method="post">
<label>Session ID</label>
<input type="text" name="session-id"><br>
<label>Songs</label><br>
<input type="text" name="song-key[]"><input type="checkbox" name="is-partial[]"><input type="checkbox" name="is-jam[]"><br>
<input type="text" name="song-key[]"><input type="checkbox" name="is-partial[]"><input type="checkbox" name="is-jam[]"><br>
<input type="text" name="song-key[]"><input type="checkbox" name="is-partial[]"><input type="checkbox" name="is-jam[]"><br>
<input type="text" name="update-date" value="<?php echo date(" Y-m-d H:i:s ");?>" hidden readonly><br>
<input type="submit" name="submit" value="Submit">
</form>
The desired result, assuming the ID has been set and a unique song entered for each of the them, and whatever variety on the radio buttons, would be three table rows. session-id and update-date would all be the same value, the rest would be unique based on entry.
This is what I currently have, but it only inserts the last of the three songs.
for ($i=0; $i < count($_POST['song-key']); $i++ ) {
$sessionkey = mysqli_real_escape_string($connection, $_POST["session-key"]);
$songkey = mysqli_real_escape_string($connection, $_POST["song-key"][$i]);
$partial = mysqli_real_escape_string($connection, isset($_POST['is-partial'][$i])) ? 1 : 0;
$jam = mysqli_real_escape_string($connection, isset($_POST['is-jam'][$i])) ? 1 : 0;
$updated = mysqli_real_escape_string($connection, $_POST["update-date"]);
$sql = "INSERT INTO session_songs (session_key, song_key, is_partial, is_jam, last_updated)
VALUES ('$sessionkey', '$songkey', '$partial', '$jam', '$updated')";
}
What do I need to change to ensure all three (or more) are entered?
If you alter your input names, you can get a more useful $_POST array.
<input type="text" name="songs[0][key]">
<input type="checkbox" name="songs[0][is-partial]">
<input type="checkbox" name="songs[0][is-jam]"><br>
<input type="text" name="songs[1][key]">
<input type="checkbox" name="songs[1][is-partial]">
<input type="checkbox" name="songs[1][is-jam]"><br>
<input type="text" name="songs[2][key]">
<input type="checkbox" name="songs[2][is-partial]">
<input type="checkbox" name="songs[2][is-jam]"><br>
With specified keys, the checkbox type inputs will match up properly with the text inputs, where they way you have it now, they will not*, because only checked checkboxes are submitted to PHP. (Try only checking "is-partial" in the second and "is-jam" in the third row, and then var_dump($_POST), and you'll see that they both have index 0.)
If your form is structured like that, you can insert your records using a foreach loop instead of a for loop.
foreach ($_POST['songs'] as $song) {
$key = $song['key'];
$partial = isset($song['is-partial']) ? 1 : 0;
$jam = isset($song['is-jam']) ? 1 : 0;
// do the insert inside the loop rather than just building the SQL
}
The reason you're currently only getting the last one is that you're defining the SQL string inside the loop, but without executing the statement in the loop, you'll only get the values from the last iteration of the loop. Move your query execution inside the loop and you should get all three rows.
*unless they are all checked

PHP - Insert elemens into an array

I'm working on a formular, but for the moment I just want to insert into an array my elements (I have books and authors).
I can display my books with author (name + surname) with the foreach, but I can't add more elements.
Here is the code with the form.
<H1>Exercice 2</H1>
<form method="POST">
<label for"code" >Number :</label>
<input id="code" name="code" type="number" />
<label for"title">Title :</label>
<input id="title" name="title" type="text" />
<label for"author" >Author :</label>
<input id="author" name="author" type="text" />
<button type="input" type="submit">Ok</button>
$title = $_POST['title'];
$code = $_POST['code'];
$author = $_POST['author'];
$book = array();
$book['code'] = 123;
$book['title'] = "Legendes";
$book['author'] = array("David", "Gemmel");
foreach($book as $value){
$book['key'] = $value;
var_dump($book);
if (is_array($value)) {
foreach($value as $otherValue) {
echo($otherValue);
}
} else {
echo($value);
}
}
I did some searcch, but I don't think it works, it's using the array_push() method with the POST, but I don't know where I can manipulate my form into the array.
If you want some details, I'll be happy to do that =) I'm working on it, if i have some news, you will know =)
Have a nice day =)
1) Assignments are in reverse. Correct way:
$myVar = $myValue
2) You need to set the name attribute in your inputs in order to be sent:
<input id="code" type="number" name="code" />
Then you can access them like:
$_POST['code']
3) To add an element by key in an array, use:
$array['key'] = $value;
Your Exercise 2 have some mistakes :
First, your HTML inputs must have the name attribute to be retrieved by post:
<h1>Exercice 2</h1>
<form method="post">
<label>
<input name="code" type="number" />
</label>
<button type="submit">Ok</button>
</form>
With PHP, you can access to any input value using the name:
$code = $_POST['code'];
Now, I think you want to "add" several books using this HTML form without a storage system. The problem is you can not do this if for every a new request since all the elements you have in your array will be deleted each time you run a new post request. To keep this information you need to use some persistent storage system as a database or others.
Since you seem to want to keep the information for each book together, you need to use a multidimensional array - hence, you'll need to redo the whole thing. Here's a suggestion:
Form:
<h2>Exercice 2</h2>
<form method="post">
<label for"code">Number :</label>
<input id="code" name="code" type="number">
<label for"title">Title :</label>
<input id="title" name="title" type="text">
<label for"author-firstname">Author First Name:</label>
<input id="author-firstname" name="author-firstname" type="text">
<label for "author-lastname">Author Last Name:</label>
<input id="author-lastname" name="author-lastname" type="text">
<input type="submit" name="submit_book" value="Ok">
</form>
Fixed the name-problems, changed the heading (you never, ever use H1 for a form, H1 is strictly used for the site-wide heading/logo/name of site). Also changed the button into a simple input type="submit".
$title = $_POST['title'];
$code = $_POST['code'];
$author = $_POST['author'];
$book = []; // changed this to modern PHP version array assignment
$book[0]['code'] = 123;
$book[0]['title'] = "Legendes";
$book[0]['author-firstname'] = "David";
$book[0]['author-lastname'] = "Gemmel"; // no reason to assign a separate array for first and last name, just use two array-keys
for ($c = 0; $c <= count($book); $c++) { //changed this to a for, counting the amount of entries in the $book array
echo 'Title: '.$book[$c]['title'];
echo 'Author: '.$book[$c]['author-firstname'].' '.$book[$c]['author-lastname'];
} // the content should probably be wrapped in a container of some sort, probably a <li> (and then a <ul>-list declared before the for-loop)
Now. None of this has anything to do with putting stuff INTO the array. That would be something like this (there isn't even a point of assigning the $_POST-variables for the code you posted. But, you can do something like this:
if (isset($_POST['submit_book'])) {
$title = $_POST['title'];
$code = $_POST['code'];
$author-firstname = $_POST['author-firstname'];
$author-lastname = $_POST['author-lastname'];
// however, if all you're doing is putting this into the array, no need to assigne the $_POST to variables, you can just do this:
$temp_array = ['code'=>$_POST['code'],'title'=>$_POST['title'],'author-firstname'=>$_POST['author-firstname'],'author-lastname'=>$_POST['author-lastname']];
$book[] = $temp_array;
}
So, that would replace the assigned variables at the beginning of your code.

How do I access two arrays from a form simultaneously in php?

I receive two arrays from a form. In the .php file, I need to insert the values of each array into a column of the table.
- use the foreach loop to access the elements of one array and complete the insertion for only one column. When I do the same thing for the next array, I find that the corresponding first column elements are null in each row while for the first array, the corresponding second column elements are null. Is there anyway to avoid this and insert the array elements one after the other?
- I understand that foreach cannot be applied to two arrays so is there any other way I can access both the arrays simultaneously for insertion into a table?
Thanks.
You can use a foreach loop:
foreach($_POST['someField_1'] as $key => $value)
{
$fieldOne = $value;
$fieldTwo = $_POST['someField_2'][$key];
}
Obviously change the _POST variables to whatever you've named the fields.
As long as your field names are named something like: name="someField_1[]" and name="someField_2[]" You can use the foreach loop in this way.
EDIT
Take this HTML for your input form:
Forename: <input type="text" name="forename[]"> Surname: <input type="text" name="surname[]">
Forename: <input type="text" name="forename[]"> Surname: <input type="text" name="surname[]">
Forename: <input type="text" name="forename[]"> Surname: <input type="text" name="surname[]">
So that form allows you to enter forenames and surnames for up to 3 people. Each field has the exact same name: forename[] and surname[]
To retrieve each of the values, you would use this PHP:
foreach($_POST['forename'] as $key => $forename)
{
echo 'Forename: ' . $forename;
echo ' ';
echo 'Surname: ' . $_POST['surname'][$key] . '<br />';
}
This works because when you submit a field like forename[], with square brackets at the end, PHP will automatically convert this to an array. $key is a number which starts at 0, and goes on for however many fields there are.
PHP uses the $key to retrieve the correct fields. You could also write your HTML like this:
Forename: <input type="text" name="forename[0]"> Surname: <input type="text" name="surname[0]">
Forename: <input type="text" name="forename[1]"> Surname: <input type="text" name="surname[1]">
Forename: <input type="text" name="forename[2]"> Surname: <input type="text" name="surname[2]">
You see I've put a number between the square brackets? PHP will detect this and loop through the arrays.
You could even use a for loop:
for($i = 0; $i<count($_POST['forename']); $i++)
{
echo 'Forename: ' . $_POST['forename'][$i];
echo 'Surname: ' . $_POST['surname'][$i];
}

Iterating through set $_POST variables by type?

I have user inputs as follows:
<form action="special.php" method="post">
<input name="first1"> <input name="last1"> <input name="age1">
<input name="first2"> <input name="last2"> <input name="age2">
<input name="first3"> <input name="last3"> <input name="age3">
<input name="first4"> <input name="last4"> <input name="age4">
<input name="first5"> <input name="last5"> <input name="age5">
<input name="first6"> <input name="last6"> <input name="age6">
...
N
</form>
The amount of user inputs in the form is determined by the user; meaning, the user can add 5,10,20 additional lines to the code above, creating new input elements (following the pattern above) as they fit.
My question is, once the form gets submitted, what is an easy way to iterate and print out all the SET POST variables?
Something like:
for($i=0; $i < $numPostVars; $i++){
if(isset($_POST['first".$i."'])){
//echo all first names post variables that are set
}
}
// do the same from last names & age in separate loops
I think the trick is to name your variables slightly different, and take advantage of PHP's feature which will unpack them as arrays for you. Just use the syntax: first[1]. Then in PHP, $_POST['first']['1'] is where you will find it. You can then iterate all your "first" inputs with
foreach($_POST['first'] as $first_input) {
// ...
}
Also keep in mind that browsers may not send the field if it is empty when the user submits.
Here is what the inputs should look like in HTML:
<input name="first[1]"> <input name="last[1]"> <input name="age[1]">
As noted by user #DaveRandom, consider also a more hierarchical structure (think "rows" like from your db):
<input name="people[1][first]"> <input name="people[1][last]"> <input name="people[1][age]">
Inputs can be treated as arrays with a syntax very similar to that used in PHP:
<input name="name[1]" value="value 1">
<input name="name[2]" value="value 2">
This would result in a $_POST['name'] that looks like this:
array(
1 => "value 1",
2 => "value 2"
);
This principle can be expanded to incorporate multi-dimensional and associative arrays. So if you were to name your inputs like this:
<input name="rows[1][first]"> <input name="rows[1][last]"> <input name="rows[1][age]">
<input name="rows[2][first]"> <input name="rows[2][last]"> <input name="rows[2][age]">
...you would be able to easily iterate over $_POST['rows'] with a foreach construct. The data structure will be very similar to a set of database results.
foreach ($_POST['rows'] as $row) {
// do stuff with $row['first'], $row['last'] and $row['age'] here
}
A couple of things to note:
Unlike PHP, associative array keys in HTML do not require quotes, and using them will produce a result you may not expect. It will work, but not in the way you might think. You still need to use quotes in PHP though.
As far as I am aware, this syntax is not a W3C standard. PHP, however, always handles it as expected.

Categories