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
Related
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>  </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).
I have a form with multiple checkboxes and hidden inputs, which I'm passing to a second page using GET.
I'm then trying to retrieve the value of each checkbox and the input in a loop and echo out the combined value.
HTML:
<form action="criteria.php" method="GET">
<input name="id[]" type="hidden" value="<? echo $criteria_id; ?>" />
<input type="checkbox" name="checked[]" class="checkbox-md" id="<? echo $criteria_id; ?>" value="Y">
<button type="submit" class="btn btn-lilac" role="button">Complete</button>
</form>
PHP:
$criteria_id = $_GET['id']; //get all criteria id
$criteria_checked = $_GET['checked']; //get checked criteria id
foreach($criteria_id as $id) //get id of all checkboxes {
echo "<BR>Criteria = ".$id."Checked = ".$criteria_checked; //returns id + array?
if ($checked='Y')//check if checked {
echo "<BR>Criteria =".$id." Checked = Y";
} else {
echo "<BR>Criteria =".$id." Checked = N";
}
}
You will need to make sure that the inputs have matching array keys:
<input name="id[0]" type="hidden" . . .
<input name="checked[0]" type="checkbox" . . .
<input name="id[1]" type="hidden" . . .
<input name="checked[1]" type="checkbox" . . .
Depending on how you create these you could use the $criteria_id:
<input name="id[<? echo $criteria_id; ?>]" type="hidden" . . .
<input name="checked[<? echo $criteria_id; ?>]" type="checkbox" . . .
This way the id and checked array keys will match. All hidden inputs will be passed from the form but only the checked checkboxes, so check if the key of the id is set in the checked array:
foreach($_GET['id'] as $key => $id) {
if (isset($_GET['checked'][$key])) {
echo "<BR>Criteria =".$id." Checked = Y";
} else {
echo "<BR>Criteria =".$id." Checked = N";
}
}
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>';
}
?>
I have struggled with this issue for a majority of the day and I am really stumped.
I have this page called preview.php with the following code below. Values are being passed to this page from another page called order.php. This preview.php page allows a user to review his or her data input from order.php.
If correction is needed, the user returns to order.php to make his or her corrections. If everything looks fine, the user sends his or her orders to process.php to be processed. The information sent to process.php are hidden form fields.
For some reason that I am unable to figure out, process.php is not recognizing the hidden form field values.
Does anyone have an idea how to resolve this?
This gentle man #spencer7593 actually helped me out with this insert statement. However, each time I attempt to add a record, I get the following:
Error: custname value cannot be null
This happens because the hidden form values are null and I can't figure out why.
preview.php
?php
error_reporting(E_ALL);
echo "DEBUG POST DATA: <pre>".print_r($_POST, 1)."</pre>";
if(isset($_POST['custname']))
$custname = $_POST['custname'];
if(isset($_POST['zip']))
$zip = $_POST['zip'];
if(isset($_POST['city']))
$city = $_POST['city'];
if(isset($_POST['email']))
$email = $_POST['email'];
$address = $_POST['address'];
$rowIDs = $_POST['rowIDs'];
$row2IDs = $_POST['row2IDs'];
echo $custname .'<br>';
echo $zip .'<br> <hr width=400 align=left>';
$rowIDs = $_POST['rowIDs'];
foreach ($rowIDs as $id) {
$agentname = $_POST['agentname' . $id];
$agentaddress = $_POST['agentaddress' . $id];
$agentincome = $_POST['agentincome' . $id];
echo 'Name: '. $agentname . '<br />';
echo 'Address: '. $agentaddress . '<br />';
echo 'agentincome: '. $agentincome . '<br /><br>';
}
?>
<body>
<form action='process.php' method = 'POST'>
<input type='hidden' name='custname' value="<?php echo $custname; ?>">
<input type='hidden' name='address' value="<?php echo $address; ?>">
<input type='hidden' name='email' value="<?php echo $email; ?>">
<input type='hidden' name='city' value="<?php echo $city; ?>">
<input type='hidden' name='zip' value="<?php echo $zip; ?>">
<input type='hidden' name='agentname' value="<?php echo $agentname; ?>">
<input type='hidden' name='agentaddress' value="<?php echo $agentaddress; ?>">
<input type='hidden' name='agentincome' value="<?php echo $agentincome; ?>">
<input type="action" type="button" value="Return to data" onclick="history.go(-1);" /> | <input type="submit" value="Submit your form" />
</form>
</body>
process.php
<?php
global $wpdb;
// Database connection
$conn = mysqli_connect("localhost","myuser","mypwd","myDB");
if(!$conn) {
die('Problem in database connection: ' . mysql_error());
}
// Data insertion into database
$sql = 'INSERT INTO `myDB`.`myTable` ( `custname`'
. ', `address`, `city`, `zip`, `email` )'
. ' VALUES ( ? , ? , ? , ? , ? )';
if( $sth = mysqli_prepare($conn,$sql) ) {
mysqli_stmt_bind_param($sth,'sssss'
,$_POST["custname"]
,$_POST["address"]
,$_POST["city"]
,$_POST["zip"]
,$_POST["email"]
);
if( mysqli_stmt_execute($sth) ) {
echo '<h1>Thank you</h1> <br> Go back to the main page <a href="index.php");';
} else {
printf("Error: %s\n",mysqli_stmt_error($sth));
}
} else {
printf("Error: %s\n",mysqli_connect_error($conn));
}
?>
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>';
}