How to $POST data to a $_SESSION array - php

I am getting all types of errors on the following code. I want to post data from my form and store in a $_SESSION array for future processing
Illegal string offset 'SurveyDate'
Illegal string offset 'Income'
<input class="formFields" type="date" id="txtDateOfSurvey" name="mycensus[0][SurveyDate]"
<input class="formFields" type="numeric" id="txtIncome" name="mycensus[0][Income]"
<?php
session_start();
if( !isset($_SESSION['mycart2']))
{
$_SESSION['mycart2'] = array();
}
$_SESSION['mycart2'] = array_merge($_SESSION['mycart'], $_POST['mycensus']);
foreach($_SESSION['mycart2'] as $v)
{
echo $v['SurveyDate'] . ' was born on ' . $v['Income'] . '<br>';
}
?>
I want the array mycart2 to contain all the entries that I enter on my form.

<?php
session_start();
if(is_array(mycensus)){
$survey_date = mycensus[0]['SurveyDate'];
$Income = mycensus[0]['Income'];
}
?>
<input class="formFields" type="date" id="txtDateOfSurvey" name="survey_date" value="<?php echo $survey_date; ?>">
<input class="formFields" type="numeric" id="txtIncome" name="income" value="<?php echo $Income; ?>">
<?Php
if( !isset($_SESSION['mycart2']))
{
$_SESSION['mycart2'] = array();
}
$_SESSION['mycart2'] = array_merge($_SESSION['mycart'], $_POST['mycensus']);
foreach($_SESSION['mycart2'] as $v)
{
echo $v['SurveyDate'] . ' was born on ' . $v['Income'] . '<br>';
}
?>

Related

How do I get PHP to stop recognizing NULL values as elements in an array? [duplicate]

This question already has answers here:
How to submit data of a form with repeated field names?
(2 answers)
What is the difference between empty() , isset() and is_null() function in php?
(1 answer)
Closed 1 year ago.
This program is supposed to accept scores for 20 assignments, store them in an array, and then echo two things: the number of assignments for which a score was entered, and the total of all the scores. My issue is that no matter whether or not I enter a value for an assignment, php not only echos a label for the assignment, but it counts the empty field as part of the array and adds it to the variable I'm using to store the number of assignments for which a score has been entered. The below is the page on which the user enters their score(s), and the page below that is the page that is supposed to display their results.
<!DOCTYPE html>
<html>
<head>
<title>Assignments</title>
<link href="main.css" type="text/css" rel="stylesheet" />
</head>
<body>
<div id="content">
<h1>Enter Your Scores (0-100, 2000 possible)</h1></br>
<p>Press The "Calculate" button when finished.</p></br>
<form action="arraysolo.php" method="post">
<div id="data">
<label>Assignment 1</label>
<input type="text" name="assign1"><br />
<label>Assignment 2</label>
<input type="text" name="assign2"><br />
<label>Assignment 3</label>
<input type="text" name="assign3"><br />
<label>Assignment 4</label>
<input type="text" name="assign4"><br />
<label>Assignment 5</label>
<input type="text" name="assign5"><br />
<label>Assignment 6</label>
<input type="text" name="assign6"><br />
<label>Assignment 7</label>
<input type="text" name="assign7"><br />
<label>Assignment 8</label>
<input type="text" name="assign8"><br />
<label>Assignment 9</label>
<input type="text" name="assign9"><br />
<label>Assignment 10</label>
<input type="text" name="assign10"><br />
<label>Assignment 11</label>
<input type="text" name="assign11"><br />
<label>Assignment 12</label>
<input type="text" name="assign12"><br />
<label>Assignment 13</label>
<input type="text" name="assign13"><br />
<label>Assignment 14</label>
<input type="text" name="assign14"><br />
<label>Assignment 15</label>
<input type="text" name="assign15"><br />
<label>Assignment 16</label>
<input type="text" name="assign16"><br />
<label>Assignment 17</label>
<input type="text" name="assign17"><br />
<label>Assignment 18</label>
<input type="text" name="assign18"><br />
<label>Assignment 19</label>
<input type="text" name="assign19"><br />
<label>Assignment 20</label>
<input type="text" name="assign20"><br />
</div>
<div id="button">
<label>&nbsp </label>
<input type="submit" value="Calculate" /><br />
</div>
</form>
</div>
</body>
</html>
The below is the page which displays the users results.
<!DOCTYPE html>
<html>
<head>
<title>Your Results:</title>
<link href="main.css" type="text/css" rel="stylesheet" />
</head>
<body>
<div id="content">
<h1>Score Per Assignment:</h1></br>
<?php
$score = array();
if(!isset($_POST['assign1'])) {
$score[0] = null;
}else {
$score[0] = $_POST['assign1'];
echo "<h2>Assignment 1:</h2>" . $score[0] . "</br>";
}
if(!isset($_POST['assign2'])) {
$score[1] = null;
}else {
$score[1] = $_POST['assign2'];
echo "<h2>Assignment 2:</h2>" . $score[1] . "</br>";
}
if(!isset($_POST['assign3'])) {
$score[2] = null;
}else {
$score[2] = $_POST['assign3'];
echo "<h2>Assignment 3:</h2>" . $score[2] . "</br>";
}
if(!isset($_POST['assign4'])) {
$score[3] = null;
}else {
$score[3] = $_POST['assign4'];
echo "<h2>Assignment 4:</h2>" . $score[3] . "</br>";
}
if(!isset($_POST['assign5'])) {
$score[4] = null;
}else {
$score[4] = $_POST['assign5'];
echo "<h2>Assignment 5:</h2>" . $score[4] . "</br>";
}
if(!isset($_POST['assign6'])) {
$score[5] = null;
}else {
$score[5] = $_POST['assign6'];
echo "<h2>Assignment 6:</h2>" . $score[5] . "</br>";
}
if(!isset($_POST['assign7'])) {
$score[6] = null;
}else {
$score[6] = $_POST['assign7'];
echo "<h2>Assignment 7:</h2>" . $score[6] . "</br>";
}
if(!isset($_POST['assign8'])) {
$score[7] = null;
}else {
$score[7] = $_POST['assign8'];
echo "<h2>Assignment 8:</h2>" . $score[7] . "</br>";
}
if(!isset($_POST['assign9'])) {
$score[8] = null;
}else {
$score[8] = $_POST['assign9'];
echo "<h2>Assignment 9:</h2>" . $score[8] . "</br>";
}
if(!isset($_POST['assign10'])) {
$score[9] = null;
}else {
$score[9] = $_POST['assign10'];
echo "<h2>Assignment 10:</h2>" . $score[9] . "</br>";
}
if(!isset($_POST['assign11'])) {
$score[10] = null;
}else {
$score[10] = $_POST['assign11'];
echo "<h2>Assignment 11:</h2>" . $score[10] . "</br>";
}
if(!isset($_POST['assign12'])) {
$score[11] = null;
}else {
$score[11] = $_POST['assign12'];
echo "<h2>Assignment 12:</h2>" . $score[11] . "</br>";
}
if(!isset($_POST['assign13'])) {
$score[12] = null;
}else {
$score[12] = $_POST['assign13'];
echo "<h2>Assignment 13:</h2>" . $score[12] . "</br>";
}
if(!isset($_POST['assign14'])) {
$score[13] = null;
}else {
$score[13] = $_POST['assign14'];
echo "<h2>Assignment 14:</h2>" . $score[13] . "</br>";
}
if(!isset($_POST['assign15'])) {
$score[14] = null;
}else {
$score[14] = $_POST['assign15'];
echo "<h2>Assignment 15:</h2>" . $score[14] . "</br>";
}
if(!isset($_POST['assign16'])) {
$score[15] = null;
}else {
$score[15] = $_POST['assign16'];
echo "<h2>Assignment 16:</h2>" . $score[15] . "</br>";
}
if(!isset($_POST['assign17'])) {
$score[16] = null;
}else {
$score[16] = $_POST['assign17'];
echo "<h2>Assignment 17:</h2>" . $score[16] . "</br>";
}
if(!isset($_POST['assign18'])) {
$score[17] = null;
}else {
$score[17] = $_POST['assign18'];
echo "<h2>Assignment 18:</h2>" . $score[17] . "</br>";
}
if(!isset($_POST['assign19'])) {
$score[18] = null;
}else {
$score[18] = $_POST['assign19'];
echo "<h2>Assignment 19:</h2>" . $score[18] . "</br>";
}
if(!isset($_POST['assign20'])) {
$score[19] = null;
}else {
$score[19] = $_POST['assign20'];
echo "<h2>Assignment 20:</h2>" . $score[19] . "</br>";
}
?>
<?php
$sum = array_sum($score);
$num_elements = count($score);
echo "<h2>Assignments Completed:</h2>" . $num_elements .
"</br>";
echo "<h2>Assignments Score Total:</h2>" . $sum .
"</br>";
?>
</div>
</body>
</html>
To expand on Alex Howansky's answer, you'll need to turn your <input> fields into an array (see How do I create arrays in a HTML form? in PHP's manual).
To do that, just replace all input fields with:
<input type="text" name="assign[]"><br />
Afterwards, you can loop them like so (this would replace your PHP code in arraysolo.php):
$score = [];
foreach ($_POST['assign'] ?? [] as $key => $value) {
$is_valid = is_numeric($value) && $value >= 0 && $value <= 200;
if ($is_valid) {
$score[] = $value;
echo "<h2>Assignment " . ($key + 1) . ":</h2>" . $value . "</br>";
}
}
$sum = array_sum($score);
$num_elements = count($score);
echo "<h2>Assignments Completed:</h2>" . $num_elements . "</br>";
echo "<h2>Assignments Score Total:</h2>" . $sum . "</br>";
This way, you'll also don't have to filter for any null values (because you won't assign them in the first place).

Update several records with a foreach

I have a problem with a part of the code in which, through a foreach I go through an array and those that meet certain conditions are updated by an UPDATE value. The problem is that I try to pass the values ​​with a hidden input and only update the last value. How can I modify the code so I can do it with arrays?
try {
$add = "UPDATE calculo SET puntaje_fecha=:puntaje_fecha WHERE id_calculo=:id_calculo";
$d = $conn->prepare($add);
$d->bindParam(':puntaje_fecha', $_POST['puntaje_fecha']);
$d->bindParam(':id_calculo', $_POST['id_calculo']);
$d->execute();
} catch (PDOException $e) {
die("Error: " . $e->getMessage() . "<br>on line: " . $e->getLine() . "<br>on file: " . $e->getFile());
}
<form action="actualizar.php" method="post">
<?php foreach ($ca as $c){?>
<?php foreach ($pr as $p) {}?>
<?php if (($p['id_fecha'])==($c['nFecha'])){
//actions to be taken if the conditions are met
}?>
<input type="hidden" name="puntaje_fecha" value="<?php echo $s; ?>">
<input type="hidden" name="id_calculo" value="<?php echo $c['id_calculo']; ?>">
<?php }} ?>
<input type="submit" value="Actualiza puntos">
</form>
What I need is that in my "calculo" table all the values ​​of "puntaje_fecha" are updated as long as they meet that condition. Many people have recommended me to change the name of the input by arrays, but I do not know how to do it. Thank you very much to anyone who can help me.
You are creating only two inputs with the names of "puntaje_fecha" and "id_calculo".
So value from last iteration is posted, in order to post all values change the hidden inputs to array.
<input type="hidden" name="puntaje_fecha[]" value="<?php echo $s; ?>">
<input type="hidden" name="id_calculo[]" value="<?php echo $c['id_calculo']; ?>">
Make sure your inputs look like below by inspect element, otherwise check your data in $ca and $pr
<input type="hidden" name="puntaje_fecha[]" value="value_1">
<input type="hidden" name="id_calculo[]" value="value_1">
<input type="hidden" name="puntaje_fecha[]" value="value_2">
<input type="hidden" name="id_calculo[]" value="value_2">
<input type="hidden" name="puntaje_fecha[]" value="value_3">
<input type="hidden" name="id_calculo[]" value="value_3">
In your try block through foreach update each value in array.
try {
$puntaje_fechaArray = $_POST['puntaje_fecha'];
$id_calculoArray = $_POST['id_calculo'];
foreach ($puntaje_fechaArray as $key => $val){
$puntaje_fecha = $val[$key];
$id_calculo = $id_calculoArray[$key];
$add = "UPDATE calculo SET puntaje_fecha=:puntaje_fecha WHERE id_calculo=:id_calculo";
$d = $conn->prepare($add);
$d->bindParam(':puntaje_fecha', $puntaje_fecha );
$d->bindParam(':id_calculo', $id_calculo);
$d->execute();
}
} catch (PDOException $e) {
die("Error: " . $e->getMessage() . "<br>on line: " . $e->getLine() . "<br>on file: " . $e->getFile());
}
You can change your below code
<input type="hidden" name="puntaje_fecha" value="<?php echo $s; ?>">
<input type="hidden" name="id_calculo" value="<?php echo $c['id_calculo']; ?>">
for this:
<input type="hidden" name="puntaje_fecha[]" value="<?php echo $s; ?>">
<input type="hidden" name="id_calculo[]" value="<?php echo $c['id_calculo']; ?>">
The above treats the input forms as an array so in your controller get the data as follows:
$puntajes = $_POST["puntaje_fecha"]; //array
$idsCalculo = $_POST["id_calculo"]; //array
You can build the query with a simple foreach:
foreach($puntajes as $index => $puntaje) {
updateData($puntaje, $idsCalculo[$index]); // call the new function for update
}
function updateData($puntaje, $idCalculo) {
$add = "UPDATE calculo SET puntaje_fecha=:puntaje_fecha WHERE id_calculo=:id_calculo";
$d = $conn->prepare($add);
$d->bindParam(':puntaje_fecha', $puntaje);
$d->bindParam(':id_calculo', $idCalculo);
$d->execute();
$message = '';
if ($d->execute()) {
$message = 'DATOS ACTUALIZADOS';
} else {
$message = 'ERROR DE ACTUALIZACION';
}
} catch (PDOException $e) {
die("Error: " . $e->getMessage() . "<br>on line: " . $e->getLine() . "<br>on file: " . $e->getFile());
}
}
I hope I've helped

PHP Random Math Quiz Evaluation issue

EDIT: When I print the $answer variable by itself it always returns the correct answer of the current question.
I am currently coding a PHP script that produces a simple, but completely random math quiz. How it works is that is gets two random numbers between 0-9 and a random operator from '-', '+', '*'. The user must enter into the text box the answer of the shown question. From here it's pretty straightforward to understand.
However, the issue I am having is that no matter what the user enters the only questions that are validated as correct are ones where the answer is 0.
Here is my code so far.
<?php
require 'functions.php';
$body = "";
$score = 0;
$count = 0;
if(isset($_POST['submit']))
{
$firstDigit = $_POST['lho'];
$secondDigit = $_POST['rho'];
$operator = $_POST['op'];
$userAnswer = $_POST['answer'];
$count = $_POST['count'];
$score = $_POST['score'];
$answer = evaluate($firstDigit, $secondDigit, $operator);
if($answer == $userAnswer)
{
$count++;
$score++;
$body .= "\n<h1>Congratulations!</h1>\n\n";
$body .= "$score out of $count";
}
else
{
$count++;
$body .= "\n<h1>Sorry!</h1>\n\n";
$body .= "$score out of $count";
}
}
header( 'Content-Type: text/html; charset=utf-8');
print("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
?>
<?php
include("./header.php");
?>
<h1>Math Quiz</h1> <br /> <br />
<?php
print $body;
?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<h3><?php echo $firstDigit; ?> <?php echo $operator; ?> <?php echo $secondDigit; ?> = ?
<input type="text" name="answer" size="2" /></h3>
<p><input type="submit" name="submit" value="Try It!" />
<input type="hidden" name="lho" value="<?php echo randdigit(); ?>" />
<input type="hidden" name="rho" value="<?php echo randdigit(); ?>" />
<input type="hidden" name="op" value="<?php echo randop(); ?>" />
<input type="hidden" name="score" value="<?php echo $score++; ?>" />
<input type="hidden" name="count" value="<?php echo $count++; ?>" /></p>
</form>
<?php
include("./footer.php");
?>
My evaluate function is this:
function evaluate($d1, $d2, $op) {
switch($op) {
case '+' : // addition
$result = $d1 + $d2;
break;
case '-' : // subtraction
$result = $d1 - $d2;
break;
case '*' : // multiplication
$result = $d1 * $d2;
break;
default : // Unidentified, return safe value
$result = 0;
}
return $result;
}
Here is the randop() function and the randdigit() function:
/* Return a number in the range 0-9 inclusive
*/
function randdigit() {
return mt_rand(0,9);
} // end functionranddigit()
function randop(){
$ops = array('+', '-', '*');
// pick a random index between zero and highest index in array.
$randnum = mt_rand(0,sizeof($ops)-1);
return $ops[$randnum]; // Use the index to pick the operator
}
First on the 48th line :
<h3><?php echo $firstDigit; ?> <?php echo $operator; ?> <?php echo $secondDigit; ?> = ?
When you first load the form and until it has been submitted once,
$firstDigit, $operator, $secondDigit
Aren't set.
Then, this line wich is the equation to solve is filled with the old equation that needed to be solved AND your hidden fields are filled with new numbers, invisible to the user using randdigit() and randop().
<input type="hidden" name="lho" value="<?php echo randdigit(); ?>" />
<input type="hidden" name="rho" value="<?php echo randdigit(); ?>" />
<input type="hidden" name="op" value="<?php echo randop(); ?>" />
Here is the code that works well for me :
<?php
require 'functions.php';
$body = "";
$score = 0;
$count = 0;
$newFdigit = randdigit();
$newSdigit = randdigit();
$newOperator = randop();
if(isset($_POST['submit']))
{
$firstDigit = $_POST['lho'];
$secondDigit = $_POST['rho'];
$operator = $_POST['op'];
$userAnswer = $_POST['answer'];
$count = $_POST['count'];
$score = $_POST['score'];
$answer = evaluate($firstDigit, $secondDigit, $operator);
if($answer == $userAnswer)
{
$count++;
$score++;
$body .= "\n<h1>Congratulations!</h1>\n\n";
$body .= "$score out of $count";
}
else
{
$count++;
$body .= "\n<h1>Sorry!</h1>\n\n";
$body .= "$score out of $count";
}
}
header( 'Content-Type: text/html; charset=utf-8');
print("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
?>
<h1>Math Quiz</h1> <br /> <br />
<?php
print $body;
?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<h3><?php echo $newFdigit; ?> <?php echo $newOperator; ?> <?php echo $newSdigit; ?> = ?
<input type="text" name="answer" size="2" /></h3>
<p><input type="submit" name="submit" value="Try It!" />
<input type="hidden" name="lho" value="<?php echo $newFdigit ?>" />
<input type="hidden" name="rho" value="<?php echo $newSdigit; ?>" />
<input type="hidden" name="op" value="<?php echo $newOperator; ?>" />
<input type="hidden" name="score" value="<?php echo $score++; ?>" />
<input type="hidden" name="count" value="<?php echo $count++; ?>" /></p>
</form>

php code after "if (isset($_POST..." is not running

Exactly what the title says. My PHP written after an the an if statement to check if a text portion of a form has any value is not running. It works fine in one written earlier in my code, but not the second time.
Here is my whole code:
<?php include '../header.php'; include '../navigation.php'; ?>
<div id="pageContent">
<form name="format" method="POST" action="phpFunctions.php">
Please input date:
<input type="date" name="date" value="<?php echo date('Y-m-d'); ?>" />
<input type="submit" name"submit1" value="Format" />
</form>
<?php
if (isset($_POST['date'])) {
$new_date = $_POST['date'];
$date = new DateTime($new_date);
echo 'M-D-Y Format: ' . $date->format('m-d-Y') . '<br>';
echo 'D-M-Y Format: ' . $date->format('d-m-Y');
}
?>
<form name="stringStuff" method="POST" action="phpFunctions.php">
Enter string:
<input type="text" name"yourString">
<input type="submit" name"submit2" value="Parse" />
</form>
<?php
if (isset($_POST['yourString']) && !empty($_POST['yourString'])) {
echo 'ayyyyyy lmao';
$new_string = $_POST['theString'];
$trimmed_string = trim($new_string);
echo 'ayyyyyy lmao';
echo 'String Length: ' . strlen($new_string) . '<br>';
echo 'Trim Whitespace: ' . $trimmed_string . '<br>';
echo 'Lowercased: ' . strtolower($new_string) . '<br>';
if(strpos($new_string, 'DMACC') !== false) {
echo 'String contains DMACC';
}
else {
echo 'String does not contain DMACC';
}
}
?>
</div>
<?php include '../footer.php'; ?>
The portion of the code that isn't working is this portion after what I mentioned
if (isset($_POST['yourString']) && !empty($_POST['yourString'])) {
echo 'ayyyyyy lmao';
$new_string = $_POST['theString'];
$trimmed_string = trim($new_string);
echo 'ayyyyyy lmao';
echo 'String Length: ' . strlen($new_string) . '<br>';
echo 'Trim Whitespace: ' . $trimmed_string . '<br>';
echo 'Lowercased: ' . strtolower($new_string) . '<br>';
if(strpos($new_string, 'DMACC') !== false) {
echo 'String contains DMACC';
} else {
echo 'String does not contain DMACC';
}
}
you missed = , name="yourString"
<form name="stringStuff" method="POST" action="test_index.php">
Enter string:
<input type="text" name="yourString">
<input type="submit" name="submit2" value="Parse" />
</form>
It seems you are missing name="yourString"
<input type="text" name="yourString">
<input type="submit" name="submit2" value="Parse" />

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

Categories