Array session showing different values on different pages PHP - 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!

Related

PHP Form keep input values together to create JSON list

I have a JSON list with conditions(items) and a color associated to every condition. I'm building a form to try to update the conditions, then return to the JSON format.
Example:
<?php
?>
$JSON_list = {
"FULL":"green",
"Half-Full":"amber",
"Quarter-Full":"amber",
"Empty":"red"
}
I json_decode() this list to turn it into a php array. Then iterate through it and display the values as inputs which can be edited.
<form action="updatedata.php" method="post">
<?php
foreach($JSON_list as $condition) {
foreach($condition as $item => $color){
?>
<input type="text" name="item[]" value="<?=$item;?>">
<select name="color[]">
<option selected="selected"><?=$color;?></option>
<option>green</option>
<option>amber</option>
<option>red</option>
</select>
<br>
<?php
};
};
};
?>
<input type="submit" value="Submit Conditions">
</form>
On submission of the form, the "items" & "colors" are stored in 2 different arrays separate from each other. I iterate through each of these arrays to obtain the new values, and then concatenate them into a JSON list again.
updatedata.php:
<?php
$num = count($_POST['item']);
$i = 1;
$subs = [];
foreach($_POST["item"] as $item){
$subs["item".$i] = $item;
$i++;
};
$c = 1;
foreach($_POST["color"] as $item){
$subs["color".$c] = $item;
$c++;
};
$submit_string = "";
$a = 1;
$comma = ",";
for($x = 0; $x < $num; $x++){
if($a == $num){
$comma = "";
};
$submit_string .= "\"".$subs["item".$a]."\":"."\"".$subs["color".$a]."\"".$comma;
$a++;
};
echo "{" . $submit_string . "}";
//Prints the JSON string "FULL":"green","Half-Full":"amber","Quarter-Full":"amber","Empty":"red"
?>
My problem occurs when the "item" input is submitted with nothing, if an item has a value of "" then I don't want this entry in the JSON list. I need to delete this entry, but also the "color" associated to that item.
Is there a way to link the "items" & "numbers" from the form so I can delete both entries??
I think there is maybe a bit more to your code you are not showing us, for example with the given structure of $JSON_list the 2 nested foreach loops you have to generate the HTML would not work. Here's what I did to get your code working:
$JSON_list needs quotes and a trailing semi-colon:
$JSON_list = '{
"FULL":"green",
"Half-Full":"amber",
"Quarter-Full":"amber",
"Empty":"red"
}';
Convert it to an array:
$array = json_decode($JSON_list, true);
Generate the HTML:
<?php foreach ($array as $item => $color) { ?>
<input type="text" name="item[]" value="<?php echo $item; ?>">
<select name="color[]">
<option selected="selected"><?php echo $color; ?></option>
<option>green</option>
<option>amber</option>
<option>red</option>
</select>
<br>
<?php } ?>
Next, if you dump out what you're getting back from a form submission, it gives you an idea of how to process it. Here's the output of print_r($_POST); after the form was submitted with the "HALF-FULL" text input blank:
Array
(
[item] => Array
(
[0] => FULL
[1] =>
[2] => Quarter-Full
[3] => Empty
)
[color] => Array
(
[0] => green
[1] => amber
[2] => amber
[3] => red
)
)
So now the relation between the 2 arrays is clear, and you can see we can use the array keys to map the elements of one to the other.
// We'll store our results in this new array
$submitted = [];
// Iterate over the first array elements
foreach ($_POST['item'] as $key => $value) {
// We only want to include item/colors that were non-blank,
// so check if we got an item here
if ($value) {
// OK it wasn't blank, so let's save the result, using
// the corresponding element from the color array
$submitted[$value] = $_POST['color'][$key];
}
}
// Now we have an array of our submitted data
// print_r($submitted);
// Array
// (
// [FULL] => green
// [Quarter-Full] => amber
// [Empty] => red
// )
// You should never try to construct a JSON string manually, just
// let PHP do it for you:
$newList = json_encode($submitted);
// echo $newList;
// {"FULL":"green","Quarter-Full":"amber","Empty":"red"}

Add values and keys to session and store each individual addition (php)

I am at my wits end for last three days.
What i want to do is to code shopping-cart like functionality. So, i have two inputs that i want EACH to store in its own array.
something along the lines of:
<?php
session_start();
$input1 = [];
$input2 = [];
if(isset($_POST['submit']))
{
$input1 = $_POST['first'];
$input2 = $_POST['second'];
$_SESSION['test'] = [
'first' => array_push($input1),
'second' => array_push($input2)
];
}
var_dump($_SESSION['test']);
?>
and my html is as follows :
<form method="post">
<input type="text" name="first" value="">
<input type="text" name="second" value="">
<input type="submit" name="submit" value="array">
</form>
Now i expect the output of var_dump to be as follows:
Array(
[First] => ('Random1','Random2')
[Second] => ('Flower1','Flower2')
)
But what i get in the best case is:
Array(
[First] => Random1
[Second] => Flower1
[0] => Random2
[1] => Flower2
)
So, my question is 1) How can i add values to $_SESSION['test'] as an array
and 2) How can i store each input in it's corresponding array?
array_push takes at least two parameters: an array, and something to push into it. You're giving it the one input, and then are not pushing anything into it. Further, you're replacing your entire $_SESSION['test'] on every run, overwriting it with new (nonsense) values.
What you want is:
$_SESSION['test']['first'][] = $input1;
$_SESSION['test']['second'][] = $input2;
Append something to the end of the existing arrays, not overwrite them.

Array multi-dimensional error PHP

<?php
$ctr = 0;
foreach($rows as $row){
?>
<input type="hidden" name="client<?php echo $ctr; ?>['client_id']" value="<?php echo $row['client_id']; ?>">
<input type="hidden" name="client<?php echo $ctr; ?>['transaction_id']" value="<?php echo $row['id']; ?>">
<input style="max-width: 100px;min-width:100px;" class="form-control right" type="text" name="client<?php echo $ctr;?>['amount']" value="" />
<?php
}
?>
Update: I have included the form where $_POST coming from.
This it the output of print_r ($_POST);:
Array
(
[client0] => Array
(
['client_id'] => 1
['transaction_id'] => 1
['amount'] => 1000
['mode'] => cash
)
[client1] => Array
(
['client_id'] => 2
['transaction_id'] => 5
['amount'] => 600
['mode'] => cash
)
[client2] => Array
(
['client_id'] => 3
['transaction_id'] => 6
['amount'] => 200
['mode'] => cash
)
[save] =>
)
When I try writing this: echo $_POST['client0']['amount'];.
I'm expecting an output of 1000
but it gives me an error like this: Notice: Undefined index: amount.
So guys can you please tell me whats wrong with my code.TIA
Compare the print_r output carefully. One key is given as client0 while the next is given as 'amount'. That's because your key is actually 'amount', not amount. Because you're including unnecessary quotes in your HTML. Fix your HTML so the input name becomes:
name="client0[amount]"
(Or alternatively address the key as $_POST['client0']["'amount'"].)
And while you're at it, you may want to rename your fields to:
name="clients[0][amount]"
Because then you can simply traverse the data using:
foreach ($_POST['clients'] as $client) {
echo $client['id'], $client['amount'], ..;
}
Which is much more readable and sane.
You should use
echo $_POST['client0']['amount'];
You are using wrong variable amount_id just check it out your array having variable is "amount" so change the variable name like bellow
echo $_POST['client0']['amount'];
I hope this will help you.
Try this way ..
foreach ($_POST['client0'] as $val) {
echo $val['amount'] ;
}

Iterate PHP Array in Form Submission

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.

PHP foreach loop through multidimensional array

I have an multidimensional array, how can I use it? I want to use each separate array in a for loop.
What I want to achive is to be able to put each part in my database like
entry in db no. 0 -> 1 and 4
entry in db no. 1 -> 5 and 6
entry in db no. 2 -> 1 and 4 and 5 and 6
I have this code:
<?php
print_r($calculatie_id);
for ($i=0; $i<=3; $i++)
{
?>
<tr>
<td>
<?php
foreach ($calculatie_id[$i] as $value)
{
echo $value;
}
?>
print_r($calculatie_id); gives
Array ( [0] => Array ( [0] => 4 [1] => 6 ) [1] => Array ( [0] => 1 [1] => 5 ) [2] => Array ( [0] => 5 [1] => 6 ) [3] => )
But when using the foreach I only get 46
Some extra information:
This array is created by an multiple select in an for loop. Any other suggestions are welcome.
for ($i=0; $i<=$aantal_regels_corr; $i++)
{
?>
<tr>
<td>
<?php
// maak select name
$calculatie_id = 'calculatie_id'.$i;
// rest van formulier
if($error_vergeten[$i] == "ja"){ $error_omschr = $error_omschr_vergeten[$i]; include('includes/input_error.php'); } ?> <textarea rows="7" cols="80" name="omschrijving[]" /><?php echo $omschrijving[$i]; ?></textarea>
</td>
<td colspan="2">
<select multiple="multiple" width="50" size="7" name="<?php echo $calculatie_id ?>[]" style="width: 150px">
<?php
$sql_calc = "select id, naam, actief from sp_calculatie WHERE (offerte_id = '".$row['off_offerte']."' OR offerte_id = '".$offerte_id."') AND actief = 'ja' ORDER BY id ASC";
$res_calc = mysql_query($sql_calc,$con);
while ($row_calc = mysql_fetch_assoc($res_calc)){
?>
<option value="<?php echo $row_calc["id"] ?>"><?php if (empty($row_calc["naam"])) { echo $row_calc["id"]; } else { echo $row_calc["naam"]; } ?></option>
<?php } ?></select>
</td>
</tr>
<?php } ?>
foreach($calculatie_id as $inner_arr)
foreach($inner_arr as $value)
echo $value;
Edit: you should try to learn and understand what's going on here. Then, you can do whatever you want with the code I wrote. You said: gives 14561456 I want to use $calculatie_id0=14 $calculatie_id1=56 $calculatie_id2=1456 etc Then, you will have to do something like this:
foreach($calculatie_id as $index => $inner_arr){
echo "$calculatie_id$index = "
foreach($inner_arr as $value)
echo $value;
echo "<br/>";
}
Or you can create those variables you want (which does not make any sense for me):
foreach($calculatie_id as $index => $inner_arr){
${"calculatie_id$index"} = '';
foreach($inner_arr as $value)
${"calculatie_id$index"} .= $value;
echo ${"calculatie_id$index"}."<br/>";
}
Basically what you have is an array like this:
array(
array(
data
)
)
All you need is:
foreach($yourArray as $innerArray)
foreach($innerArray as $value)
echo $value;
That will output what you want. I'm not particularly sure why you're doing a for() loop then a foreach.
You need to nest your foreach loops (so you have a loop inside a loop)
You could try:
foreach ($calculatie_id as $key => $value) {
echo "$calculatie_id:".$key;
for ($i=0;$i<=count($value);$i++) {
echo $value[$i];
}
}
I don't understand why your original code snippet isn't working. Could it be the fact that $calculatie_id[3] is not an array?
I tried this:
<?php
$calculatie_id = array ( array(4,6), array(1,5), array(5,6), '' );
for ($i=0; $i<=3; $i++)
{
if(!is_array($calculatie_id[$i]))
continue;
echo "$i: ";
foreach ($calculatie_id[$i] as $value)
{
echo $value;
}
echo '<br/>';
}
And that prints:
0: 46
1: 15
2: 56
Many thanks for helping me out this far but all the examples I try to implement are not working.
I have been trying this script for over 2 weeks now. It seems I'm going all the wrong way.
I have put my code online at www.pws.nl/downloads/sp_offerte_add.rar. It must be easier then what I'm writing in the code right now.

Categories