Best way to submit many same-record? [duplicate] - php

I have a form like the one below which is posted to contacts.php, and the user can dynamically add more with jQuery.
<input type="text" name="name[]" />
<input type="text" name="email[]" />
<input type="text" name="name[]" />
<input type="text" name="email[]" />
<input type="text" name="name[]" />
<input type="text" name="email[]" />
If I echo them out in PHP with the code below,
$name = $_POST['name'];
$email = $_POST['account'];
foreach($name as $v) {
print $v;
}
foreach($email as $v) {
print $v;
}
I will get something like this:
name1name2name3email1email2email3
How can I get those arrays into something like the code below?
function show_Names($n, $m)
{
return("The name is $n and email is $m, thank you");
}
$a = array("name1", "name2", "name3");
$b = array("email1", "email2", "email3");
$c = array_map("show_Names", $a, $b);
print_r($c);
so my output is like this:
The name is name1 and email is email1, thank you
The name is name2 and email is email2, thank you
The name is name3 and email is email3, thank you

They are already in arrays: $name is an array, as is $email
So all you need to do is add a bit of processing to attack both arrays:
$name = $_POST['name'];
$email = $_POST['account'];
foreach( $name as $key => $n ) {
print "The name is " . $n . " and email is " . $email[$key] . ", thank you\n";
}
To handle more inputs, just extend the pattern:
$name = $_POST['name'];
$email = $_POST['account'];
$location = $_POST['location'];
foreach( $name as $key => $n ) {
print "The name is " . $n . ", email is " . $email[$key] .
", and location is " . $location[$key] . ". Thank you\n";
}

E.g. by naming the fields like
<input type="text" name="item[0][name]" />
<input type="text" name="item[0][email]" />
<input type="text" name="item[1][name]" />
<input type="text" name="item[1][email]" />
<input type="text" name="item[2][name]" />
<input type="text" name="item[2][email]" />
(which is also possible when adding elements via JavaScript)
The corresponding PHP script might look like
function show_Names($e)
{
return "The name is $e[name] and email is $e[email], thank you";
}
$c = array_map("show_Names", $_POST['item']);
print_r($c);

You could do something such as this:
function AddToArray ($post_information) {
//Create the return array
$return = array();
//Iterate through the array passed
foreach ($post_information as $key => $value) {
//Append the key and value to the array, e.g.
//$_POST['keys'] = "values" would be in the array as "keys"=>"values"
$return[$key] = $value;
}
//Return the created array
return $return;
}
The test with:
if (isset($_POST['submit'])) {
var_dump(AddToArray($_POST));
}
This for me produced:
array (size=1)
0 =>
array (size=5)
'stake' => string '0' (length=1)
'odds' => string '' (length=0)
'ew' => string 'false' (length=5)
'ew_deduction' => string '' (length=0)
'submit' => string 'Open' (length=4)

I came across this problem as well. Given 3 inputs: field[], field2[], field3[]
You can access each of these fields dynamically. Since each field will be an array, the related fields will all share the same array key. For example, given input data:
Bob, bob#bob.com, male
Mark, mark#mark.com, male
Bob and his email and sex will share the same key. With this in mind, you can access the data in a for loop like this:
for($x = 0; $x < count($first_name); $x++ )
{
echo $first_name[$x];
echo $email[$x];
echo $sex[$x];
echo "<br/>";
}
This scales as well. All you need to do is add your respective array vars whenever you need new fields to be added.

You can use an array of fieldsets:
<fieldset>
<input type="text" name="item[1]" />
<input type="text" name="item[2]" />
<input type="hidden" name="fset[]"/>
</fieldset>
<fieldset>
<input type="text" name="item[3]" />
<input type="text" name="item[4]" />
<input type="hidden" name="fset[]"/>
</fieldset>
I added a hidden field to count the number of the fieldsets.
The user can add or delete the fields and then save it.

However, VolkerK's solution is the best to avoid miss couple between email and username. So you have to generate HTML code with PHP like this:
<? foreach ($i = 0; $i < $total_data; $i++) : ?>
<input type="text" name="name[<?= $i ?>]" />
<input type="text" name="email[<?= $i ?>]" />
<? endforeach; ?>
Change $total_data to suit your needs. To show it, just like this:
$output = array_map(create_function('$name, $email', 'return "The name is $name and email is $email, thank you.";'), $_POST['name'], $_POST['email']);
echo implode('<br>', $output);
Assuming the data was sent using POST method.

This is an easy one:
foreach($_POST['field'] as $num => $val) {
print ' ' . $num . ' -> ' . $val . ' ';
}

Already is an array.
My inputs are:
<input name="name[]" value='joe'>
<input name="lastname[]" value='doe'>
<input name="name[]" value='jose'>
<input name="lastname[]" value='morrison'>
In the $_POST data, returns the following:
[name] => Array
(
[0] => 'joe'
[1] => 'jose'
)
[lastname] => Array
(
[0] => 'doe'
[1] => 'morrison'
)
You can access to these data, in the following way:
$names = $_POST['name']
$lastnames = $_POST['lastname']
// accessing
echo $names[0]; // joe
This way It is very useful for creating pivot tables.

Using this method should work:
$name = $_POST['name'];
$email = $_POST['account'];
while($explore=each($email)) {
echo $explore['key'];
echo "-";
echo $explore['value'];
echo "<br/>";
}

Related

set if choice is correct for each input field using checkbox in php mysql [duplicate]

I have a form like the one below which is posted to contacts.php, and the user can dynamically add more with jQuery.
<input type="text" name="name[]" />
<input type="text" name="email[]" />
<input type="text" name="name[]" />
<input type="text" name="email[]" />
<input type="text" name="name[]" />
<input type="text" name="email[]" />
If I echo them out in PHP with the code below,
$name = $_POST['name'];
$email = $_POST['account'];
foreach($name as $v) {
print $v;
}
foreach($email as $v) {
print $v;
}
I will get something like this:
name1name2name3email1email2email3
How can I get those arrays into something like the code below?
function show_Names($n, $m)
{
return("The name is $n and email is $m, thank you");
}
$a = array("name1", "name2", "name3");
$b = array("email1", "email2", "email3");
$c = array_map("show_Names", $a, $b);
print_r($c);
so my output is like this:
The name is name1 and email is email1, thank you
The name is name2 and email is email2, thank you
The name is name3 and email is email3, thank you
They are already in arrays: $name is an array, as is $email
So all you need to do is add a bit of processing to attack both arrays:
$name = $_POST['name'];
$email = $_POST['account'];
foreach( $name as $key => $n ) {
print "The name is " . $n . " and email is " . $email[$key] . ", thank you\n";
}
To handle more inputs, just extend the pattern:
$name = $_POST['name'];
$email = $_POST['account'];
$location = $_POST['location'];
foreach( $name as $key => $n ) {
print "The name is " . $n . ", email is " . $email[$key] .
", and location is " . $location[$key] . ". Thank you\n";
}
E.g. by naming the fields like
<input type="text" name="item[0][name]" />
<input type="text" name="item[0][email]" />
<input type="text" name="item[1][name]" />
<input type="text" name="item[1][email]" />
<input type="text" name="item[2][name]" />
<input type="text" name="item[2][email]" />
(which is also possible when adding elements via JavaScript)
The corresponding PHP script might look like
function show_Names($e)
{
return "The name is $e[name] and email is $e[email], thank you";
}
$c = array_map("show_Names", $_POST['item']);
print_r($c);
You could do something such as this:
function AddToArray ($post_information) {
//Create the return array
$return = array();
//Iterate through the array passed
foreach ($post_information as $key => $value) {
//Append the key and value to the array, e.g.
//$_POST['keys'] = "values" would be in the array as "keys"=>"values"
$return[$key] = $value;
}
//Return the created array
return $return;
}
The test with:
if (isset($_POST['submit'])) {
var_dump(AddToArray($_POST));
}
This for me produced:
array (size=1)
0 =>
array (size=5)
'stake' => string '0' (length=1)
'odds' => string '' (length=0)
'ew' => string 'false' (length=5)
'ew_deduction' => string '' (length=0)
'submit' => string 'Open' (length=4)
I came across this problem as well. Given 3 inputs: field[], field2[], field3[]
You can access each of these fields dynamically. Since each field will be an array, the related fields will all share the same array key. For example, given input data:
Bob, bob#bob.com, male
Mark, mark#mark.com, male
Bob and his email and sex will share the same key. With this in mind, you can access the data in a for loop like this:
for($x = 0; $x < count($first_name); $x++ )
{
echo $first_name[$x];
echo $email[$x];
echo $sex[$x];
echo "<br/>";
}
This scales as well. All you need to do is add your respective array vars whenever you need new fields to be added.
You can use an array of fieldsets:
<fieldset>
<input type="text" name="item[1]" />
<input type="text" name="item[2]" />
<input type="hidden" name="fset[]"/>
</fieldset>
<fieldset>
<input type="text" name="item[3]" />
<input type="text" name="item[4]" />
<input type="hidden" name="fset[]"/>
</fieldset>
I added a hidden field to count the number of the fieldsets.
The user can add or delete the fields and then save it.
However, VolkerK's solution is the best to avoid miss couple between email and username. So you have to generate HTML code with PHP like this:
<? foreach ($i = 0; $i < $total_data; $i++) : ?>
<input type="text" name="name[<?= $i ?>]" />
<input type="text" name="email[<?= $i ?>]" />
<? endforeach; ?>
Change $total_data to suit your needs. To show it, just like this:
$output = array_map(create_function('$name, $email', 'return "The name is $name and email is $email, thank you.";'), $_POST['name'], $_POST['email']);
echo implode('<br>', $output);
Assuming the data was sent using POST method.
This is an easy one:
foreach($_POST['field'] as $num => $val) {
print ' ' . $num . ' -> ' . $val . ' ';
}
Already is an array.
My inputs are:
<input name="name[]" value='joe'>
<input name="lastname[]" value='doe'>
<input name="name[]" value='jose'>
<input name="lastname[]" value='morrison'>
In the $_POST data, returns the following:
[name] => Array
(
[0] => 'joe'
[1] => 'jose'
)
[lastname] => Array
(
[0] => 'doe'
[1] => 'morrison'
)
You can access to these data, in the following way:
$names = $_POST['name']
$lastnames = $_POST['lastname']
// accessing
echo $names[0]; // joe
This way It is very useful for creating pivot tables.
Using this method should work:
$name = $_POST['name'];
$email = $_POST['account'];
while($explore=each($email)) {
echo $explore['key'];
echo "-";
echo $explore['value'];
echo "<br/>";
}

Update batch using checkbox, failed

I want to update the data using array and checkbox. If the checkbox checked, status become "1". Else, leave it "0".
I have try something like this
<?php
foreach($report as $r){;
?>
<input type="checkbox" name="status[]" value="1" value="<?php echo $r->status;?>">
<input type="hidden" name="id_name[]" value="<?php echo $r->id_name;?>">
<input type="hidden" name="name[]" value="<?php echo $r->name;?>">
<?php } ?>
and this
<input type="checkbox" name="status[]" value="1">
<input type="hidden" name="id_name[]" value="<?php echo $r->id_name;?>">
<input type="hidden" name="name[]" value="<?php echo $r->name;?>">
But both of them update the first row even I check the third or the fourth row.
my controller is something like this
function update_approval() {
$status = $this->input->post('status');
$id_name = $this->input->post('id_name');
$name = $this->input->post('name');
for($a=0; $a< sizeof ($id_name); $a++) {
$data[$a] = array(
'status' => $status[$a],
'id_name' => $id_name[$a],
'name' => $name[$a]
);
}
$this->db->update_batch('tbl_m_name', $data, 'id_name');
}
Thanks in advance
I've solved it. Thanks,
I change the position, here is my views
<input type="checkbox" name="id_name[]" value="<?php echo $r->id_name;?>">
<input type="hidden" name="name[]" value="<?php echo $r->name;?>">
and here is my controller
function update_approval() {
$id_name = $this->input->post('id_name');
$name = $this->input->post('name');
$data[$a] = array();
for($a=0; $a< sizeof ($id_name); $a++) {
$data[] = array(
'status' => 1,
'id_name' => $id_name[$a],
'name' => $name[$a]
);
}
$this->db->update_batch('tbl_m_name', $data, 'id_name');
}
so if I check the box, it will post the id_name that I choose
thanks, but I had tried yours, I get undefinied variable $a. So, I changed the position and removed $data[$a]= array(); . Below is my code (after resolve my problem) based on yours:
function update_approval() {
$id_name = $this->input->post('id_name');
$name = $this->input->post('name');
for($a=0; $a< sizeof ($id_name); $a++) {
$data[$a] = array(
'status' => 1,
'id_name' => $id_name[$a],
'name' => $name[$a]
);
}
$this->db->update_batch('tbl_m_name', $data, 'id_name');
}

How to get two arrays values within one foreach()

There are two values I want to get from user that is name and price. I have made an auto generating rows function that generate input boxes with same name. Now the thing is I want to store them in database. I using foreach but that only get one array. I want to store both name as well as price. How can I do that. Here is my code.
HTML Form
<form method="post">
<input type="text" name="name[]" /><input type="text" name="price[]" />
<input type="text" name="name[]" /><input type="text" name="price[]" />
<input type="text" name="name[]" /><input type="text" name="price[]" />
<input type="text" name="name[]" /><input type="text" name="price[]" />
<input type="submit" value="Submit" name="submit" />
</form>
PHP Code
if(isset($_POST['submit']))
{
foreach($_POST['name'] as $name)
{
echo $name;
}
}
Call the index in the loop as well and then select the corresponding value from the other array.
foreach($_POST['name'] as $id => $name)
{
echo $name;
echo $_POST['price'][$id]
}
How about this
if(isset($_POST['submit']))
{
$names = $_POST['name']; # array
$prices = $_POST['price']; # array
foreach($names as $id => $name)
{
echo $name;
echo "<br>";
echo $prices[$id]
}
}
Provided you know both arrays will be the same length, a simple for loop will do:
if(isset($_POST['submit']) && count($_POST['name']) == count($_POST['price']))
{
for($i=0; $i < count($_POST['name']); $i++)
{
echo $_POST['name'][$i] . ' ' . $_POST['price'][$i];
}
}
Try this
$names = array_combine($_POST['name'], $_POST['price']);
foreach($names as $firstname => $price) {
echo $firstname . ' ' . $price . '<br>';
}

I need to write a program for my class will keep score of a bowling game

I need to write a PHP program that will keep score of a bowling game. I can handle the calculation of the scores that is not the problem. My problem is getting the data into arrays in the first place.
My idea is to have an array for each player like below:
$scores = array(
array(
'name' => 'Player 1',
'sheet' => '10,10,10,10,10,10,10,10,10,10,10,10'
),
array(
'name' => 'Player 2',
'sheet' => '10,10,10,10,10,10,10,10,10,10,10,10'
),
);
I wanted to have an initial form where you can enter the player names, this then creates the arrays and afterwards create another form for each player (array) to enter the scores.
What would be the best way to go about doing this?
Thanks
Edit: Will this work?
<input maxlength="30" name="players[1][player1]" size="30" type="text" />
<input maxlength="30" name="players[2][player2]" size="30" type="text" />
So the first form as show above will create the arrays and the the player name value. The second form like the below would add the scores, although I cant seem to get this to work.
<input maxlength="30" name="players[1][score]" size="30" type="text" />
<input maxlength="30" name="players[2][score]" size="30" type="text" />
Here is a small example. Perhaps buggy but it should work (for inspiration)
<h1>Bowling</h1>
<?php
if ( isset ( $_POST['next'] ) ) {
if ( isset ( $_POST['players'] ) ) {
$exp = explode("\n", trim($_POST['players']));
echo "<h2>Input Score</h2>";
echo '<form method="post" action="bowling.php">';
foreach ( $exp as $p ) {
if ( trim($p) != '') {
$name = trim(htmlspecialchars($p));
echo '<fieldset>';
echo '<label><h3>Input "' .$name.'" score</h3></label>';
echo '<input style="width:100%" type="text" name="score[]" placeholder="Put in the score for ' . $name . '. Just for example 1 2 3 4 5">';
echo '<input type="hidden" name="player[]" value="'.$name.'">';
echo '</fieldset>';
}
}
echo '<input type="submit" name="next" value="Results">';
echo '</form>';
}
if ( isset($_POST['score'], $_POST['player']) ) {
echo "<h2>Results</h2>";
$i = 0;
$result = [];
foreach ( $_POST['player'] as $name ) {
$result[$name] = $_POST['score'][$i];
$i++;
}
var_dump($result);
}
} else {
?>
<form method="post" action="bowling.php">
<textarea style="width:500px; height:500px;" name="players" placeholder="One player in each line and everything will be fine"></textarea>
<input name="next" type="submit">
</form>
<?php
} ?>

PHP: How to correctly loop through multi-dimen post arrays

If I have a form with fields like this.
THERE WILL BE MULTIPLE ROWS OF THESE FIELDS HENCE THE SQUARE BRACKETS
<input type="text" name="txt-receipt-number[]" value="" />
<input type="text" name="txt-stock-number[]" value="" />
<input type="text" name="txt-repair-code[]" value="" />
How do I loop through the $_POST variable to get the values because its getting the field names but not the values, what am I doing wrong please?
$fields = array();
$values = array();
foreach($_POST as $field => $value) {
$fields[] = $field;
echo $value;
}
Output:
ArrayArrayArrayArrayArrayArrayArrayArrayArray
Update:
Sorry, quick edit for correct output...
Further Update:
Lets ignore the insert, how do I get the values please?
Remove the [] of your text input, or you will get $value of array type.
<input type="text" name="txt-receipt-number" value="" />
<input type="text" name="txt-stock-number" value="" />
<input type="text" name="txt-repair-code" value="" />
And don't forget to quote your values.
foreach($_POST as $field => $value)
{
if(is_array($value))
{
foreach($value as $k => $val)
{
echo $val;
}
}
else
{
echo $value;
}
}
Works for regular fields and one-dimensional _POST fields.
You will have some other problems though, with column names like sales_receipt-number, etc. You should enclose those in backquotes, and you must also escape them since they are going directly into your SQL statement. They are just as vulnerable to SQL injection as the VALUES().
$fields[] = "`" . mysql_real_escape_string($field) . "`";
Update 2
To get the values and do the insert in a loop, the SQL needs to be reconstructed each time in the loop, using one set of array values.
// Find the number of loops necessary
// Unless all fields are always required, this will need to be the $_POST key with the most values
$numLoops = count($_POST['txt-receipt-number']);
fields = array();
$values = array();
for ($i = 0; $i < count($_POST); $i++) {
foreach($_POST as $field => $value) {
$fields[] = "`" . mysql_real_escape_string($field) . "`";
$values[] = mysql_real_escape_string($_POST[$field][$i]);
// Now build the SQL for this loop iteration.
$sql = 'insert into table(' . join(',', $fields) . ') values(' . join(',', $values) . ')';
}
}
To be honest, I see many problems in this code...
Using foreach to build dynamic list of fields that need to be inserted. Don't you have, for example, anything like <input type='submit' name='add_data'/>? It's common to have submit buttons, and, with your code, you would try to edit DB table's field named add_data. This is also unsafe, as it (a) reveals table structure and (b) gives possibility to make SQL errors by manually changing field names, which may lead to another security/stability issues.
Lack of escaping field names. May lead to SQL injections.
Using - sign in field names. insert into table(sales_receipt-number, ... just won't work.
As for handling posted arrays...
<form method='post' action=''>
<table border='1'>
<tr>
<td><input type='text' name='receipt_number[]'/></td>
<td><input type='text' name='stock_number[]'/></td>
<td><input type='text' name='repair_code[]'/></td>
</tr>
<tr>
<td><input type='text' name='receipt_number[]'/></td>
<td><input type='text' name='stock_number[]'/></td>
<td><input type='text' name='repair_code[]'/></td>
</tr>
<tr>
<td><input type='text' name='receipt_number[]'/></td>
<td><input type='text' name='stock_number[]'/></td>
<td><input type='text' name='repair_code[]'/></td>
</tr>
<tr>
<td colspan='3'>
<input type='submit' name='add_items'/>
</td>
</tr>
</table>
</form>
<pre>
<?php
function handleAddingItem() {
if ( !isset($_POST['receipt_number'], $_POST['stock_number'], $_POST['repair_code']) ) {
trigger_error("Some field is undefined");
return false;
}
if ( !is_array($_POST['receipt_number']) || !is_array($_POST['stock_number']) || !is_array($_POST['repair_code']) ) {
trigger_error("Some field is not an array");
return false;
}
$keys = array_keys($_POST['receipt_number']);
if ( array_keys($_POST['stock_number']) !== $keys || array_keys($_POST['repair_code']) !== $keys ) {
trigger_error("Posted arrays have different keys");
return false;
}
foreach ( $keys as $key ) {
if ( empty($_POST['receipt_number'][$key]) && empty($_POST['stock_number'][$key]) && empty($_POST['repair_code'][$key]) ) {
continue;
}
$receiptNumber = mysql_real_escape_string($_POST['receipt_number'][$key]);
$stockNumber = mysql_real_escape_string($_POST['stock_number'][$key]);
$repairCode = mysql_real_escape_string($_POST['repair_code'][$key]);
$sql = "
insert into table_name set
receipt_number = '{$receiptNumber}',
stock_number = '{$stockNumber}',
repair_code = '{$repairCode}'
";
echo $sql;
}
return true;
}
function handlePost() {
print_r($_POST);
if ( isset($_POST['add_items']) ) {
handleAddingItem();
}
}
if ( $_SERVER['REQUEST_METHOD'] === 'POST' ) {
handlePost();
}
?>
Output:
Array
(
[receipt_number] => Array
(
[0] => 123
[1] =>
[2] =>
)
[stock_number] => Array
(
[0] =>
[1] =>
[2] =>
)
[repair_code] => Array
(
[0] =>
[1] =>
[2] =>
)
[add_items] => Submit Query
)
insert into table_name set
receipt_number = '123',
stock_number = '',
repair_code = ''
Common practice might be to pass additional field - row's ID. If it has a value, then action is "edit", if it is empty, action is "create".
This is a little bit strange but try it :
<?php
foreach($_POST['txt-receipt-number'] as $k=>$v){
$array[$k]['txt-receipt-number'] = $_POST['txt-receipt-number'][$k];
$array[$k]['txt-stock-number'] = $_POST['txt-stock-number'][$k];
$array[$k]['txt-repair-code'] = $_POST['txt-repair-code'][$k];
}
$fields = array();
$values = array();
foreach($array as $row) {
foreach($row as $field => $value) {
$values[] = $value;
$fields[] = $field;
}
}
var_dump($fields);
var_dump($values);
?>
<form method='post' action=''>
<input type="text" name="txt-receipt-number[]" value="" /><br>
<input type="text" name="txt-stock-number[]" value="" /><br>
<input type="text" name="txt-repair-code[]" value="" /><br>
----
<input type="text" name="txt-receipt-number[]" value="" /><br>
<input type="text" name="txt-stock-number[]" value="" /><br>
<input type="text" name="txt-repair-code[]" value="" /><br>
<input type="submit" value="go">
</form>

Categories