How to get two arrays values within one foreach() - php

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>';
}

Related

PHP- how to get values from checked checkboxes and corresponding textboxes

I want to get three values separated by a comma when the form is submitted. The value from the checkbox, textbox 1 and textbox 2.
This is my code that retrieves values from mysql database and generates checkboxes and two corresponding textboxes.
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<?php
$query = "SELECT * FROM subject";
$data = mysqli_query($con, $query);
while ($row = mysqli_fetch_array($data)){
$s = $row['sub'];
echo $s;
?>
<input type="checkbox" name="req_sub[]" value= "<?php echo $s; ?>" />
<input type="text" name="<?php echo $s; ?>" placeholder="Total Number" />
<input type="text" name="<?php echo $s; ?>" placeholder="Pass Number" />
<?php
}
?>
<input type="submit" name="submit" value="Add">
</form>
Suppose the user checks the first three boxes , and enters the values like in this picture -
when I click add, I get the values --
Physics
Math
Chemistry
by using the code below:
<?php
if (isset($_POST['submit'])) {
if (!empty($_POST['req_sub'])) {
foreach ($_POST['req_sub'] as $selected) {
echo $selected."</br>";
}
}
}
?>
but how do I get the values like this-
Physics,40,30
Math,40,30
Chemistry,30,25
I want this output in a variable so that I can store it in my database table.
I have spent several hours behind this in last few days. Please help me with this one.
you need to assign unique names to the <input type="text" ... /> so you can recieve its values in the PHP.
Second, you need to write PHP code, that's concatenating those values.
For example, your HTML code might be:
<input type="checkbox" name="req_sub[]" value= "<?php echo $s; ?>" />
<input type="text" name="total[<?php echo $s; ?>]" placeholder="Total Number" />
<input type="text" name="pass[<?php echo $s; ?>]" placeholder="Pass Number" />
and your PHP code might be:
if (isset($_POST['submit'])) {
if (!empty($_POST['req_sub'])) {
foreach ($_POST['req_sub'] as $selected) {
$total = $_POST['total'][$selected];
$pass = $_POST['pass'][$selected];
$var = $selected . ',' . $total . ',' . $pass;
echo $var . '<br />';
}
}
}

Working with checkbox from form array in php

Am looping products out from product table to add them to cart table. only the selected product by checking the checkbox should be added, but if you select, the selected ones do not correspond..
HERE IS THE HTML GETTING THE PRODUCTS OUT
<html>
<form action="#" id="" class="horizontal-form" method="post">
<?php
$LISTP = "SELECT * FROM products ORDER BY id";
$sn = 0;
$stmt = $pdo->prepare($LISTP);
$stmt->execute();
while($list = $stmt->fetch(PDO::FETCH_ASSOC)){
$sn = $sn + 1;
$ID = $list['id'];
$NAME = $list['name'];
?>
<input type="checkbox" name="slected[]" class="checkboxes" value="1" />
<input type="hidden" name="productid[]" class="" value="<?php echo $ID;?>" />
<input type="text" name="name[]" class="" value="<?php echo $NAME;?>" />
<?php }?> </form>
<?php
// now when we submot the form
$slected = $_POST['slected'];
$prod = $_POST['productid'];
$name = $_POST['name'];
foreach($prod as $key => $product){
if($slected[$key]>0){
echo $product.' '.$name[$key].' '.#$slected[#$key].'--<br>';
}
// the problem is here, if you check all product it will work well, but if you check the second one
// it would echo the second one giving it the name of the first one which was not checked at all
?>
I used to do this the same way in the past, and have discovered what I think is a better way. Rather than having a hidden input that stores the ID, just use the ID as the index for all of the form variable keys:
<input type="checkbox" name="slected[<?php echo $ID; ?>]" class="checkboxes" value="1" />
<input type="text" name="name[<?php echo $ID; ?>]" class="" value="<?php echo $NAME;?>" />
Then, your PHP can be simplified:
// now when we submot the form
$slected = $_POST['slected'];
$name = $_POST['name'];
foreach( (array)$slected as $ID => $on ) {
echo $product . ' ' . $name[$ID] . ' ' . $ID . '--<br>';
}
So - basically, your $slected variable will contain an array of only items that are selected, AND you have the product ID built in to the $slected array.

php: how to shorten many $_POST[];

I'm working on a page with many insert fields.
how can i shorten the following code?
$title_1 = $_POST['title_1'];
$content_1 = $_POST['content_1'];
$link_1 = $_POST['link_1'];
$img_link_1 = $_POST['img_link_1'];
$title_2 = $_POST['title_2'];
$content_2 = $_POST['content_2'];
$link_2 = $_POST['link_2'];
$img_link_2 = $_POST['img_link_2'];
$title_3 = $_POST['title_3'];
$content_3 = $_POST['content_3'];
$link_3 = $_POST['link_3'];
$img_link_3 = $_POST['img_link_3'];
You could loop through the $_POST array like this:
foreach ($_POST as $key => $value) {
${$key} = $value;
}
This will make your post variable like $_POST['title_1'] into $title_1
Remember your post names will have to be the exact names you want your variables to be referenced by.
I would do:
$howmany = 3; // How many sets of fields are submitted.
for($i=0;$i<$howmany;$i++){
$field[$i]['title'] = $_POST['title_'.$i];
$field[$i]['content'] = $_POST['content_'.$i];
$field[$i]['link'] = $_POST['link_'.$i];
$field[$i]['img_link'] = $_POST['img_link_'.$i];
}
Then you can access data in $field[1]['title'] form.
You can use extract (http://php.net/manual/en/function.extract.php): extract($_POST)
But you should be careful -- what if the client POSTs user_id, or something? At the least, you should specify that $_POST values won't overwrite already-defined variables: extract($_POST, EXTR_SKIP)
I redid this answer after you edited your post. Use variable variables.
foreach ($_POST as $key => $val)
{
if (preg_match('/^(([a-z]+_)+\d)$/', $key, $match)
{
$$match[0] = $val;
}
}
Use [a-z0-9] or [a-zA-Z0-9] as alternatives.
<?php
$key_prefixes = array (
'title',
'content',
'link',
'img_link'
);
$i = 1;
while (true) {
$post_values_missing = 0;
foreach ($key_prefixes as $key_prefix) {
$key = $key_prefix . '_' . $i;
if (!isset($_POST[$key])) {
$post_values_missing += 1;
continue;
};
$val = $_POST[$key];
// do something with $val
}
// did you get any values through this iteration?
$post_values_exist_bool = (count($key_prefixes) !== $post_values_missing);
// if not, you must've gotten them all
if (false === $post_values_exist_bool) {
break;
}
$i += 1;
}
The cleanest way to do this would be to use PHP's POST data processing capabilities to do the work for you.
Consider using your HTML form names as follows:
<form action="{url}" method="post">
<input type="text" name="data[0][title]" />
<input type="text" name="data[0][content]" />
<input type="text" name="data[0][link]" />
<input type="text" name="data[0][image_link]" />
<input type="text" name="data[1][title]" />
<input type="text" name="data[1][content]" />
<input type="text" name="data[1][link]" />
<input type="text" name="data[1][image_link]" />
...
</form>
In PHP extract the data as follows:
$data = $_POST['data'];
This shortens your PHP code to just one line. This statement will directly give you an array in PHP of the data form input. A var_dump will look as follows:
array (
0 => array('title'=>'...','content'=>'...','link'=>'...','image_link'=>'...'),
1 => array('title'=>'...','content'=>'...','link'=>'...','image_link'=>'...'),
...
)
You don't have to change your name, just make it array;
<input type="text" name="title[]" />
<input type="text" name="content[]" />
<input type="text" name="link[]" />
<input type="text" name="image_link[]" />
<input type="text" name="title[]" />
<input type="text" name="content[]" />
<input type="text" name="link[]" />
<input type="text" name="image_link[]" />
<input type="text" name="title[]" />
<input type="text" name="content[]" />
<input type="text" name="link[]" />
<input type="text" name="image_link[]" />
PHP:
extract($_POST);
$count=count($title);
for($i=0;$i<$count;$i++) {
//You can perform your any function on this loop, to get title use $title[$i]
}

dynamic form submitting

I have in the form like
<form action="sub.php" method="post">
<input type="text" name="username[]"><br>
<input type="text" name="hometown[]"><br>
<input type="text" name="country[]"><br>
<input type="submit" value="submit">
</form>
sub.php
$username = $_POST["username"];
foreach($_POST['username'] AS $ID => $Value){
echo "Checkbox with value ".$sValue." was checked!<br>";
}
I could get only one one input field i.e., username
Can we get all 3inputs to sub.php
If I understand the question
<form action="sub.php" method="post">
<input type="text" name="user[1][name]"><br>
<input type="text" name="user[1][hometown]"><br>
<input type="text" name="user[1][country]"><br>
<input type="text" name="user[2][name]"><br>
<input type="text" name="user[2][hometown]"><br>
<input type="text" name="user[2][country]"><br>
<input type="submit" value="submit">
</form>
PHP
$users = $_POST["user"];
foreach($users AS $ID => $info){
echo "user $ID ({$info['name']}) lives in {$info['hometown']}<br>"; // dollar symbol added
}
echo "all usernames: ";
$all_ids = array_keys($users);
foreach($all_ids as $current_id) {
echo $users[$current_id]['name']." ";
}
I'm not sure what your question is but there are a few issues with your html. It should be the following:
<form action="sub.php" method="post">
<input type="text" name="username"><br>
<input type="text" name="hometown"><br>
<input type="text" name="country"><br>
<input type="submit" value="submit>
</form>
I removed the brackets from the fields because brackets normally imply that you want your php code to see it as an array of values but you have single text fields.
If you want to get all of the inputs from the form you should use:
foreach($_POST AS $ID => $Value){
echo "Textbox with value ". $Value ." was used!<br>";
}
I changed it to textbox because your form doesn't have any checkboxes
try this (not elegant but should show you where its going wrong..)
$username = $_POST["username"];
foreach($_POST['username'] AS $ID => $Value){
echo "Checkbox with value ".$Value." was checked!<br>";
}
$hometown = $_POST["hometown"];
foreach($_POST['hometown'] AS $ht_ID => $ht_Value){
echo "Checkbox with value ".$ht_Value." was checked!<br>";
}
$username = $_POST["country"];
foreach($_POST['country'] AS $c_ID => $c_Value){
echo "Checkbox with value ".$c_Value." was checked!<br>";
}
If you have equal # of username,hometown,country and in correct sequence, then you can use following way
foreach($_POST['username'] AS $ID => $Value){
echo "Username ".$Value." was checked!<br>";
echo "Hometown ".$_POST['hometown'][$ID]." was checked!<br>";
echo "Country ".$_POST['country'][$ID]." was checked!<br>";
}

changing a lists sort order inline

I have a list
Each row has a common input field "sort_order" that's stored in MySQL db.
<input name="sort_order" type="text" value="<?php echo $cat['sort_order']; ?>" size="3" />
I want to be able to change the sort order inline, without going into the edit form.
How do I get all the values into the database. I think I need to loop through each row adding the sort_order[row_id] and value to an array. But I am stuck on how to achieve this.
all the values are posting according to firePHP. sort_order[50] 1, sort_order[51] 2 etc.
New Attempt at explaining:
I have a list view with 2 input fields.
<input name="cat_id" type="hidden" value="<?php echo $cat['cat_id']; ?>" />
<input name="sort_order" type="text" value="<?php echo $cat['sort_order']; ?>" size="3" />
I have a function that's called on post in the controller:
public function sortOrderUpdate(){
//collect the values of cat_id and sort_order from each input into a array
//$this->request->post['sort_order']
//$this->request->post['cat_id']
//send to the model
$this->model_cat->updateCatSortOrder($sortorderarray);
}
And the database model file function:
public function updateCatSortOrder($sortorderarray){
foreach((int)$sortorderarray as $sort){
$this->db->query("UPDATE cat SET sort_order='" . (int)$sort['sort_order'] . "' WHERE cat_id = '" . (int)$sort['cat_id'] . "'");
}
}
Whats the best way to achieve this?
Just use empty square brackets:
<input type="text" name="sort_order[]" value"<?php echo $sort_order; ?>" />
You can then access the input as an array, saving you from building it yourself. It'll be stored as $_POST['sort_order'] (or $_GET, depending on the method attribute specified in your <form> tag).
On a related note, you should probably escape $sort_order when echoing it:
<input type="text" name="sort_order[]" value"<?php echo htmlspecialchars($sort_order); ?>" />
i would not recommend using [ ] in html names.
<input type="text" name="sort_order_<?php echo $row_id; ?>" value"<?php echo $sort_order; ?>" />
say, you have 50 input fields, when posted, you can build an array this way:
$sortorder = array();
for($i=0; $i<50; $i++){
$sortorder[] = $_REQUEST['sort_order_' . $i];
}
Ok this seems to work:
<input name="cat_id[]" type="hidden" value="<?php echo $cat['cat_id']; ?>" />
<input name="sort_order[]" type="text" value="<?php echo $cat['sort_order']; ?>" size="3" />
Controller:
public function updateCatSortOrder(){
$sortvals = $this->request->post['sort_order']; //$this->request->post same as $_POST
$row = $this->request->post['cat_id'];
$n = count($this->request->post['cat_id']);
$sortorder = array();
for($i=0; $i<$n; $i++){
$sortorder[] = array(
'cat_id' => $row[$i],
'sort_order' => $sortvals[$i]
);
}
$this->model_cat->updateCatSortOrder($sortorder);
}
Model:
//UPDATE CAT SORT ORDER
public function updateCatSortOrder($sortorder){
foreach($sortorder as $sort){
$this->db->query("UPDATE cat SET sort_order='" . $this->db->escape($sort['sort_order']) . "' WHERE cat_id = '" . $this->db->escape($sort['cat_id']). "'");
}
}

Categories