Iterate PHP Array in Form Submission - php

I have an HTML form that's submitting to a PHP script and send it as an email.
The problem I'm having is iterating the array and getting the output formatted into a table correctly.
My input fields look like this:
<input class="form-control" type="text" name="alternate[][qty]" />
<input class="form-control" type="text" name="alternate[][height]" />
I am iterating the array like this:
if ( isset( $_POST['alternate']))
{
foreach($_POST['alternate'] as $alt)
{
$message .= "<tr><td>" . $alt['qty'] . "</td><td>" . $alt['height'] . "</td></tr>";
}
}
I'm getting the correct values from the array but they are not formatted correctly. I am looking for an output something like this:
123 45
but instead it breaks across two rows like this:
How can I get both values on the same line?
EDIT:
Using
echo '<pre>';
print_r($_POST['alternate']);
echo '</pre>';
I get
Array
(
[0] => Array
(
[qty] => 54
)
[1] => Array
(
[height] => 5
)
[2] => Array
(
[qty] => 34
)
[3] => Array
(
[height] => 5
)
[4] => Array
(
[qty] => 36
)
[5] => Array
(
[height] => 45
)
...
)
which makes it look like I actually have 6 arrays...? That would explain why I'm getting each cell on a separate row, but I still don't understand how to fix it...

You're iterating through every element in $_POST['alternate'] and creating a row for each iteration. There are two elements, thus two rows.
There's no need to iterate since you already know which elements you'll get:
if ( isset( $_POST['alternate']))
{
$message = "<tr><td>{$_POST['alternate']['qty']}</td><td>{$_POST['alternate']['height']}</td></tr>";
}

Give this a shot, I hope that's what you're opting for.
if(isset($_POST['alternate']))
{
$message = "<tr>";
foreach($_POST['alternate'] as $alt)
{
if(isset($alt['qty']))
$message .= "<td>" . $alt['qty'] . "</td>";
elseif(isset($alt['height']))
$message .= "<td>" . $alt['height'] . "</td>";
}
$message .= "</tr>";
}
This gave me <tr><td>123</td><td>45</td></tr>.
EDITED SOLUTION
This script actually takes care of <tr> tags inside of the loop.
if(isset($_POST['alternate']))
{
foreach($_POST['alternate'] as $alt)
{
if(isset($alt['qty']))
$message .= "<tr><td>" . $alt['qty'] . "</td>";
elseif(isset($alt['height']))
$message .= "<td>" . $alt['height'] . "</td></tr>";
}
}
Try it out and let me know.

Your HTML actually declares separate array entries. You need to group them by defining keys for the array. Something like:
<input class="form-control" type="text" name="alternate[0][qty]" />
<input class="form-control" type="text" name="alternate[0][height]" />
Then the next group of fields uses "1" and so on.

Related

Array session showing different values on different pages PHP

For context, I'm relevantly new to PHP and am trying to develop a simple quiz application but came across a roadblock which I just can't seem to find any solutions to for many hours. In short, I'm using a session to store an array of question ID's and answers for reference on another page, but when I print the array on the other page, the values of both sessions are completely different and I'm not sure what I'm doing wrong.
Additionally, the correct answers are always wrong and seem to check with the different session. Below are the relevant snippet of codes, session_start() is included in both.
quiz.php
<form method="post" action = "">
<div class="align-items-center justify-content-center">
<?php
$data = getQuestion($link,$_SESSION['typeSelected'],$_SESSION["questionCount"]); // sql query function
$i = 1;
$answers = array();
$ids = array();
while($row = mysqli_fetch_array($data)) {
$answers[] = (int) $row['answer'];
$ids[] = (int) $row['id'];
echo $answers[$i-1] . "<br>" . $ids[$i-1] . "<br>"; // shows correct answer row and question ID from database for my reference
echo " <div class = \"question-div\">
<h3><label>" . $i . ". " . $row['info'] . "</label></h3>
</div>
<div>
<h4><label class=\"form-check-label\">
<input name=\"answer$i\" class=\"form-check-input\" type=\"radio\" value=1 > ".$row['one'].
"</label></h4>
</div>
<div>
<h4><label class=\"form-check-label\">
<input name=\"answer$i\" class=\"form-check-input\" type=\"radio\" value=2> ".$row['two']."
</label></h4>
</div>
<div>
<h4><label class=\"form-check-label\">
<input name=\"answer$i\" class=\"form-check-input\" type=\"radio\" value=3> ".$row['three']."
</label></h4>
</div>
<div>
<h4><label class=\"form-check-label\">
<input name=\"answer$i\" class=\"form-check-input\" type=\"radio\" value=4> ".$row['four']."
</label></h4>
</div>";
$i++;
}
?>
</div>
<input name="submit" type="submit" class="btn-primary" value="Submit">
</form>
<?php
$_SESSION["ids1"] = $ids; // creates a new session from array of questions asked
$_SESSION["answer1"] = $answers; // creates a new session with the array of correct answers
print_r($_SESSION["ids1"]); // eg: prints Array ( [0] => 32 [1] => 18 [2] => 24 [3] => 25 [4] => 19 )
echo "<br>";
print_r($_SESSION["answer1"]); // eg: prints Array ( [0] => 4 [1] => 2 [2] => 4 [3] => 3 [4] => 3 )
$point = 0;
$wrongs = array();
if(isset($_POST["submit"])) {
for($a=1; $a < $i; $a++) {
if(isset($_POST["answer$a"]) && ($_POST["answer$a"] == $_SESSION["answer1"][$a-1])) { // always incorrect and seems to check with the different session array shown on result.php
$point++;
}
else {
$wrongs[] = $ids[$a-1];
}
}
$_SESSION["test"] = $_POST["answer1"]; // for me to check value of option selected
$_SESSION["point"] = $point;
$_SESSION["wrongs"] = $wrongs;
setPoint($link,$_SESSION["email"],$point);
echo "<script>window.location.href='result.php';</script>";
}
?>
result.php
print_r($_SESSION['ids1']); // eg: prints Array ( [0] => 18 [1] => 23 [2] => 33 [3] => 19 [4] => 32 )
echo "<br>";
print_r($_SESSION['answer1']); // eg: prints Array ( [0] => 2 [1] => 1 [2] => 1 [3] => 3 [4] => 4 )
// arrays printed on each website have correct question and answer pairs, but I still don't understand why the sessions are different
Sorry if this was a little lengthy, it's my first time posting here and I'm at my wits end, having tried everything I could think of but can't see the solution. Any help would be greatly appreciated!

PHP - Parsing nested JSON array values

I have hit a wall and I am not sure what is causing this. I am parsing a JSON file and creating variables. All the ones that are not nested in arrays work great. These two below are not though and I am not sure why. $hail var value shows for both the hail and the $wind var and I am completely puzzled as to why.
Here is a snippet of the code to create the variable from the value.
$hail = isset($currFeature['properties']['parameters']['hailSize'][0]);
$wind = isset($currFeature['properties']['parameters']['windGust'][0]);
Here is how it is outputted and displayed in the HTML which it displays but shows $hail for both var.
<div class="alerts-description"> HAZARDS<br /><? if (isset($hail)) {echo $hail . '" Hail';} ?><br /> <? if (isset($wind)) {echo $wind . '" MPH Winds';} ?></div>
Example of array as both hailSize and windGust is nested under parameters and both [0]
[response] => Avoid
[parameters] => Array
(
[hailSize] => Array
(
[0] => 0.50
)
[windGust] => Array
(
[0] => 70
)
[VTEC] => Array
(
[0] => /O.NEW.KFWD.FA.W.0008.170813T1318Z-170813T1615Z/
)
[EAS-ORG] => Array
(
[0] => WXR
)
Any suggestions what I am doing wrong or am missing?
EDIT: Link to example code just hit the "Run it" button"
http://rextester.com/EELE62798
-Thanks!
$hail = isset($currFeature['properties']['parameters']['hailSize'][0]);
The above code will generate a variable with the value true or false. It will never have the value from your data.
The following PHP7 code is a possible solution.
<?php
$json = '{"properties":{"parameters":{"hailSize":[0.50],"windGust":[70]}}}';
$currFeature = json_decode($json, true);
$hail = $currFeature['properties']['parameters']['hailSize'][0] ?? null;
$wind = $currFeature['properties']['parameters']['windGust'][0] ?? null;
// check specifically for null
if ( $hail !== null ) {
echo $hail . '" Hail'. PHP_EOL;
}
// check specifically for null
if ( $wind !== null ) {
echo $wind . '" MPH Winds'. PHP_EOL;
}
if ( empty($currFeature['properties']['parameters']['windGust'][1]) ) {
echo "empty also works to check for missing data\n";
}
if ( ! isset($currFeature['properties']['parameters']['windGust'][1]) ) {
echo "isset to check for missing data\n";
}
If you run it on the command line you will get the following output:
0.5" Hail
70" MPH Winds
empty also works to check for missing data
isset to check for missing data

2D array PHP variables in between words

As the title says. I'm trying to store every value from $_POST['spell'.$j.'icon'.$i] inside a 2d array and I'm curious if there is any way to make this array look the same way so $spell[$j]icon[$i]
$spellicon=array();
for($i=1;$i<=$_POST['champ_number']; $i++){
for($j=1; $j<=$noofspellschamp[$i]; $j++){
$spellicon[$j][$i]=$_POST['spell'.$j.'icon'.$i];
}
}
EDIT Bit of code from the previous site. Data is nested so I need it to be in 2d array.
for($i=1;$i<=$champ_number; $i++){
echo $_POST['champno'.$i].'<br/>';
//echo '<input type="hidden" value="'.$_POST['champno'.$i].'" name="champno'.$i.'">';
$champno[$i] = $_POST['champno'.$i];
//echo '<input type="hidden" value="'.$_POST['noofspellschamp'.$i].'" name="noofspellschamp'.$i.'">';
$noofspellschamp[$i] = $_POST['noofspellschamp'.$i];
for($j=1; $j<=$_POST['noofspellschamp'.$i]; $j++){
echo '<select name="spell'.$j.'icon'.$i.'">';
echo '<option value="Passive">Passive</option>';
echo '<option value="Q" selected>Q</option>';
echo '<option value="W">W</option>';
echo '<option value="E">E</option>';
echo '<option value="R">R</option>';
echo '</select>';
if($i==1&&$j==1){
echo '<input type="text" name="spell'.$j.'title'.$i.'" placeholder="Spell '.$j.' name" required autofocus><br/>';
}
else{
echo '<input type="text" name="spell'.$j.'title'.$i.'" placeholder="Spell '.$j.' name" required><br/>';
}
Edit 2 Print_R($_POST)
Array (
[formid] => 6
[champ_number] => 2
[spell1icon1] => Q
[spell1title1] => spell1
[champno1spellno1] => 1
[description111] => sakdop
[change111] => buff
[spell1icon2] => Q
[spell1title2] => sdkop
[champno2spellno1] => 1
[description121] => sadas
[change121] => buff
[noofspellschamp] => {"1":"1","2":"1"}
[champno] => {"1":"Garen","2":"Katarina"}
[patch] => 0.03
)
There's no such thing as $spell[$j]icon[$i] in PHP. The approach you're using($spellicon[$j][$i]) is the only one in standard PHP (I mean, without classes).
But it'll be better if you do it like this: $spellicon[$i][$j], because it's the champion that has the spells, and not the other way around.
Code below is simplification. Check included topic. Just use
$_POST['spellicon'][$j][$i]
or
$_POST['spell'][$j]['icon'][$i]
and the you will have same naming convention as your variable.
Considering form building it will be cleaner and you can group your data with good manner. If you don't know how to send multidimensional arrays via POST, check this topic

php multidimensional array how to get values

This is my php array $data.
Array
(
[upcoming] => Array
(
[webinars] => Array
(
[0] => Array
(
[webinarKey] => 123456
[subject] => webinar title ...
[times] => Array
(
[0] => Array
(
[startTime] => 2014-04-03T00:00:00Z
Please check my code below. I want to get values of "webinarkey" and "subject" and "start date - with date formatted" and put them into my select box. I can now populate "webinarkey and "subject". Thank you all to help to to populate "webinarkey and subject" but now i want to show "start date with date format as well.
echo '<form method="POST"><select>';
foreach ($data["upcoming"]["webinars"] as $webinar) {
echo '<option value="' . htmlspecialchars($webinar["webinarKey"]) . '">' . htmlspecialchars($webinar["subject"]) . htmlspecialchars($webinar["times"]["startTime"]) . '</option>';
}
echo '</select></form>';
Please help me to show start date as well.
$data = array(/**/);
foreach ($data["upcoming"]["webinars"] as $webinar) {
echo '<option value="' . htmlspecialchars($webinar["webinarKey"]) . '">' . htmlspecialchars($webinar["subject"]) . '</option>';
}
From what I gather the only array you need to loop over is $data["upcoming"]["webinars"].
Ensure your output HTML is valid and your data is escaped properly.
Since you are trying to access a value in a multidimensional array, you cannot use -> as that is for properties of objects. Instead you need to access it like a normal array: $array[key]
Updated Code:
echo '<select>';
foreach ($webinars as $obj)
{
foreach ($obj['webinars'] as $ob)
{
echo '<option value='.$ob['webinarKey'].'>'.$ob['subject'].'</option>';
}
}
echo '</select>';
You're trying to use properties, it's an array not an object.
You need to use $ob['----'] instead of $ob-> notation
echo '<select>';
foreach ($webinars as $obj)
{
foreach ($obj['webinars'] as $ob)
{
echo '<option value='.$ob['webinarKey'].'>'.$ob['subject'].'</option>';
}
}
echo '</select>';

PHP Arrays and Form Values

PHP noob here. I am using PHP to present a supply order form. The list of supplies that can be ordered are dynamic, so I'm pulling them from a MySQL database. Here is the PHP code that is generating the HTML form fields by looping through the results of the query:
while($row = mysqli_fetch_array($itemresult))
{
echo "<input type='hidden' name='Item_ID[]' value='" . $row['Item_ID'] . "'></TD>";
echo "<TR><TD class='itemdesc'>" . $row['Item_Name'] . " </TD>";
echo "<input type='hidden' name='Item_Name[]' value='" . $row['Item_Name'] . "'></TD>";
echo "<TD>" . $row['Item_Qty'] . " </TD>";
echo "<TD class='itemprice'>" . $row['Price'] . " </TD>";
echo "<input type='hidden' name='Item_Price[]' value='" . $row['Price'] . "'></TD>";
echo "<TD><input type='text' size='3' name='Order_Qty[]'></TD>";
echo "<TD><input type='checkbox' name='Off_Day[]'></TD>";
}
I have no experience using arrays, however it makes sense that I need these form values passed to my process.php file in an array format. For now, the purpose of my process.php is to simply print a list of Item_Name and the associated Order_Qty by themselves, pretty much like:
Pencils 10
Pens 7
and on and on.
Being new to arrays and PHP, I have no idea how to accomplish this in my process.php files and would appreciate some guidance. Thanks!
+++++++++++++++++++++++++++++++++++++++++++++++
*#yknivag*
Thank you! That helps me understand me the structure. I've been testing various foreach examples online, am hitting a roadblock and could use some additional help. My array result looks like this.
[Item_Name] => Array (
[0] => One Item
[1] => Second Item
[2] => Third Item
[3] => Fourth Item )
[Item_Price] => Array (
[0] => 0.00
[1] => 64.50
[2] => 110.00
[3] => 38.45 )
How do I reference a particular value in the array, such as 'Second Item'? I can't seem to figure out the syntax for referencing a particular item. For instance, this statement returns no data.
echo "Item: " . $_POST[Item_Name] . "<BR>";
What would also be helpful, is to know how to display corresponding array items such as 'Second Item' and '64.50' together?
The following foreach loop seems like it should do the trick, however it doesn't return any data either.
foreach ($myarray as $key => $value)
{
echo "<p>".$key." ".$value."</p>";
}
Everything I've read says this should give me what I want, and I'm confused as to why it's returning nothing.
In your process.php file begin with:
<?php
print "<pre>" . PHP_EOL;
print_r($_POST);
print "</pre>" . PHP_EOL;
?>
Then you will see the structure of the data which is being sent back and that should help you to work out how to process it.
Once you have the structure, examine the foreach command.
You want an associative array
array("pencil" => 9.99, "pen" => 3.23, "paper" => 21.11)
If you are submitting your form through AJAX, you would use JavaScript to post the values to your PHP page.
var pencil = document.getElementById("pencil").value;
var pen = document.getElementById("pen").value;
var paper = document.getElementById("paper").value;
$.post("process.php", {pencil: pencil, pen: pen, paper: paper});
On your "process" page, you would grab the values that were posted
$pencil = $_POST["pencil"];
$pen = $_POST["pen"];
$paper = $_POST["paper"];
then build your array with the following
$myarray = array("pencil" => $pencil, "pen" => $pen, "paper" => $paper);
Edit
In your WHILE loop, build yourself an array by putting this at the end
$myarray[$name] = $price;
Then outside of the loop, encode your array into a JSON object
$myjson = json_encode($myarray, JSON_HEX_APOS);
Now that you have a JSON object, you'll need to grab it in JavaScript
var myjson = <?php echo $myjson; ?>;
Then you can do whatever you want with the key / value pairs
for(var key in myjson){
var item_name = key;
var item_price = myjson[key];
//where the magic happens
}

Categories