php form saves only the last input field value - php

I have a simple table "Exams" with the columns id, title and a form with a variable amount of exam input fields.
But when one submit the form the last value will be saved triple times.
I suppose it's because of the $sql_insert statement with the same value.
How can i change the code that the different values are submitted in that $sql_insert statement?
echo '<form action="" method="post">';
for ($i = 1; $i <= $student['passed_exams']; ++$i) {
echo '<label>Exams '.$i.' :</label>';
echo '<input type="text" id="id['.$i.']" name="title" placeholder="passed Exam" />';
echo '<br />';
}
echo '<input type="submit" value=" Submit " name="submit" /></form>';
if (isset($_POST['submit'])) {
for ($i = 0; $i < $student['passed_exams']; ++$i) {
$sql_insert = "INSERT INTO exams (title) VALUES ('".$_POST['title']."')";
$dbConnection->query($sql_insert);
}
$dbConnection->close();
}

Php needs name as an array
echo '<form action="" method="post">';
for ($i = 1; $i <= $student['passed_exams']; ++$i) {
echo '<label>Exams '.$i.' :</label>';
echo '<input type="text" id="id['.$i.']" name="title['.$i.']" placeholder="passed Exam" />';
echo '<br />';
}
echo '<input type="submit" value=" Submit " name="submit" /></form>';
if (isset($_POST['submit'])) {
for ($i = 0; $i < $student['passed_exams']; ++$i) {
$sql_insert = "INSERT INTO exams (title) VALUES ('".$_POST['title'][$i]."')";
$dbConnection->query($sql_insert);
}
$dbConnection->close();
}

You need to make the title array first as
name="title['.$id.']"
Then you have to save it as
$_POST['title'][$id]

Related

Adding variables to database with a for loop

My main question is why is PDO::exec not executing every iteration of my loop, and instead only executing in the first iteration.
I am trying to insert coordinates into my MySQL database.
My database structure is (number(primary key), x, y, z).
I ask the user to insert a number ($n), and then ask them to fill in $n sets of coordinates.
The users inputs are passed to another page with $_POST, then retrieved by dynamic variable names and inserted into the database.
Everything works, except the loop only writes to the database its first iteration. So I end up with results for x1,z1,y1 but nothing else.
Can anyone explain what I am doing wrong (other than not using arrays)?
<?php
require_once('db.php');
$n = $_POST['selectOption'];
for($i = 1; $i < $n+1;$i++){
${'x' . $i} = $_POST["x" . $i];
${'y' . $i} = $_POST["y" . $i];
${'z' . $i} = $_POST["z" . $i];
$rowsAffected = $db->exec("INSERT INTO coordinate3d (number,x,y,z)
VALUES ('$n', '${'x' . $i}', '${'y' . $i}', '${'z' . $i}')");
}
?>
Here is my form
<form action="aaron_stockdale_dynamic_process.php" method="post" name="coordinateForm">
<?php
for($i = 0; $i < $n; $i++)
{
?>
x<?php echo $i+1;?> <input name="x<?php echo $i+1;?>" type=text>, y<?php echo $i+1;?> <input name="y<?php echo $i+1;?>" type=text>, z<?php echo $i+1;?> <input name="z<?php echo $i+1;?>" type=text><br>
<?php
}
?>
<br>
<input type="hidden" name="selectOption" value="<?php echo $n;?>">
<input type="submit" oonClick="document.location.href='aaron_stockdale_dynamic_process.php'" value="Submit">
</form>
require_once('aaron_stockdale_database.php');
$n = $_POST['selectOption'];
for($i = 1; $i < $n+1;$i++){
$x = $_POST["x" . $i];
$y = $_POST["y" . $i];
$z = $_POST["z" . $i];
$rowsAffected = $db->exec("INSERT INTO coordinate3d (number,x,y,z)
VALUES ('$n', '$x', '$y', '$z')");
}
the rest is on you ;)
And also check if any of the fields a primary key, that will prevent insert it twice.
Since you have received an acceptable answer for your question, I'd like to give you a hint on your html code.
<form action="aaron_stockdale_dynamic_process.php" method="post" name="coordinateForm">
<?php
for($i = 0; $i < $n; $i++)
{
?>
x<?php echo $i+1;?> <input name="x<?php echo $i+1;?>" type=text>, y<?php echo $i+1;?> <input name="y<?php echo $i+1;?>" type=text>, z<?php echo $i+1;?> <input name="z<?php echo $i+1;?>" type=text><br>
<?php
}
?>
<br>
<input type="hidden" name="selectOption" value="<?php echo $n;?>">
<input type="submit" oonClick="document.location.href='aaron_stockdale_dynamic_process.php'" value="Submit">
</form>
Now, this code can be cleaned up a bit.
<form action="aaron_stockdale_dynamic_process.php" method="post" name="coordinateForm">
<?php
for($i = 0; $i < $n; $i++)
{
echo 'x' . $i+1 . '<input name="x' . $i+1 . '" type=text>, y' . $i+1 . ' <input name="y' . $i+1. '" type=text>, z' . $i+1 . '<input name="z' . $i+1 . '" type=text><br>'
}
?>
<br>
<input type="hidden" name="selectOption" value="<?php echo $n;?>">
<input type="submit" value="Submit">
</form>
I changed the "oonClick" to "onClick", and then afterwards I removed it, as when you submit, you don't need to navigate, as the browser will do this, upon submission.
And then I removed the repetitive opening and closing of php tags, and combined all the echos into one.
Here's my solution in one file:
<!DOCTYPE html>
<html lang=en>
<head>
<script>
function validcoord(e) {
var key;
var keychar;
if (window.event)
key = window.event.keyCode;
else if (e)
key = e.which;
else
return true;
keychar = String.fromCharCode(key);
keychar = keychar.toLowerCase();
// control keys
if ((key==null) || (key==0) || (key==8) || (key==9) || (key==13) || (key==27) )
return true;
// Numeral Characters
else if ((("0123456789-.,").indexOf(keychar) > -1))
return true;
else
return false;
}
</script>
<style>
input[type="number"] { text-align: right; width: 50px; }
label { margin-left: 4em; }
</style>
</head>
<body>
<?php
define ("SELF", $_SERVER['PHP_SELF']);
define ("EOL", "\r\n");
// Modify as needed
define ("MINNUMCORDS" , "1");
define ("MAXNUMCORDS" , "10");
define ("DFLTNUMCORDS", "2");
$formSubmitted = (empty($_POST)) ? FALSE : TRUE;
if (!$formSubmitted) {
$htmlOutput = '
<form action="' . SELF . '" method=post name=foo id=foo>
<input type=hidden name=current value=0>
<label>Enter the number of Coordinates:
<input type=number autofocus onFocus="this.select()"' .
' min=' . MINNUMCORDS .
' max=' . MAXNUMCORDS .
' value=' . DFLTNUMCORDS .
' name=numcords /></label>
</form>' . EOL;
echo $htmlOutput;
} // end if not submitted
else { // a form HAS been submitted
foreach ($_POST as $key => $value) { $$key = $value; }
unset($_POST);
if (!empty($coord)) { // We got some input that may be a valid x,y,z coordinate
if ( substr_count($coord, ",") != 2 ) {
$error = "We're looking for THREE numbers seperated by TWO commas.";
} // end if we don't have three values
else { // We got three Values
$coord = trim($coord);
list($x,$y,$z) = explode(",", $coord);
if ( !(is_numeric($x) && is_numeric($y) && is_numeric($z)) ) {
$error = "We're looking for three VALID NUMBERS seperated by two commas.";
} // end if all three numbers are not valid
else { // We got three Values and each of them are numbers
require('db.php');
$rowsAffected = $db->exec("INSERT INTO coordinate3d (number,x,y,z)
VALUES ('$numcords', '$x', '$y', '$z')");
//echo "INSERT INTO coordinate3d (number,x,y,z) VALUES ('$numcords', '$x', '$y', '$z')<br />" . EOL;
} // end three valid numbers
} // end three values
} // end if we have some input in $coord
if ($error) {
echo "~~ " . $error . "<br /><br />" . EOL;
--$current;
} // end if error
if ( $current < $numcords ) {
$htmlOutput = 'Please enter the coordinate in the form: x,y,z (Ex: -.4,2,8.5)' . EOL;
$htmlOutput .= '<form action="' . SELF . '" method=post name=bar id=bar>' . EOL;
$htmlOutput .= ' <input type=hidden name=numcords value="' . $numcords . '" />' . EOL;
$htmlOutput .= ' <input type=hidden name=current value="' . ++$current . '" />' . EOL;
$htmlOutput .= ' <label>Coord #' . $current . ': ';
$htmlOutput .= '<input type=text name=coord size=12 maxlength=48 ' .
'autofocus onKeyPress="return validcoord(event);" /></label>' . EOL;
$htmlOutput .= '</form>' . EOL;
echo $htmlOutput;
} // end if we need to get another coord
} // end form was submitted
?>
</body>
</html>

How to adress the right html input field with php

I would like to delete an user from a file. I generate the html form with the php code. Now, it reads the user from a file ann puts it in a email input field. When I click the delete button after the user I choose, it should delete him out of the file. But I don't know how to do it that it takes the right user, because I generate it with a for.
From where does the php choose if the button is clicked?
By the way the $liste is an Array with all the users in it.
echo '<form id=\"myform\" name=\"myform\">';
for ($j = 0; $j < count($liste); $j++) {
echo '<input id=\"email\" type=\"email\" name=\"email\" required=\"required\" value=' . $liste[$j][0] . '>';
echo '<select name="permission">
<option value="admin">admin</option>
<option value="user">user</option>
</select>';
echo '<input type=\'submit\' name=\'submit\'>';
echo '<input type=\'submit\' name=\'delete\' value=\'delete\'>';
echo '</form>';
if(isset($_GET['submit'])){
echo "Option doesn't work yet";
}}
if(isset($_GET['delete'])){
for ($i = 0; $i < count($liste); $i++){
if ($liste[$i][0] == $liste[j][0]){
echo $liste[$i][0].'deleted';
}
}
}
Ok for the beggining you having some syntax to fix in your form tag (missing method to get and action to some page)
for ($j = 0; $j < count($liste); $j++) {
echo "<form id=\"myform\" name=\"myform\" action=\"\" method=\"GET\">";
echo '<input id=\"email\" type=\"email\" name=\"email\" required=\"required\" value=' . $liste[$j][0] . '>';
echo '<select name="permission">
<option value="admin">admin</option>
<option value="user">user</option>
</select>';
echo '<input type=\'submit\' name=\'submit\'>';
echo '<input type=\'submit\' name=\'delete\' value=\'delete\'>';
echo '</form>';
}
if(isset($_GET['submit'])){
echo "Option doesn't work yet";
}
if(isset($_GET['delete'])){
for ($i = 0; $i < count($liste); $i++){
if ($liste[$i][0] == $liste[j][0]){
echo $liste[$i][0].'deleted';
}
}
}

Enter values through a form into array, PHP

I'm trying to have a number of forms with one field each and make the input enter in to the same array.
This is my code:
<?php
$parts = array();
for($i = 0; $i < "10"; $i++)
{
echo '<form action="index.php" method="post">';
echo '<input type="text" name="parts[]"><br>';
echo '<input type="submit">';
echo '</form>';
$parts[$i] = $_POST['holder'];
unset($_POST['holder']);
}
$arrlength = count($parts);
for($i = 0; $i < $arrlength; $i++) {
echo $parts[$i];
echo "<br>";
}
?>
As of right now the number I choose at random was 10 it's supposed to be any given number by the user, but this is just for test purposes.
The problem I'm having is that it only posts the last part, I've tried a bunch of different ways but none have been successful so far.
It sounds like you want to submit a form with multiple entries in an array?
You would need to do it something like:
echo '<form action="index.php" method="post">';
for($i = 0; $i < "10"; $i++)
{
echo '<input type="text" name="parts['.$x.']"><br>';
}
echo '<input type="submit">';
echo '</form>';
Then in the code that you are posting to
var_dump($_POST['parts']);

Pass Additional Variable in Option Selected form

I have a loop that creates options in a drop down form.
How can I pass the variable $objectID[$i] from the loop where $i consistent with the selected value $i
echo '<form action="#" method="post"><select name="Restaurant">';
for ($i = 0; $i < count($restaurants); $i++){
$name[$i] = $restaurants[$i]->get("Name");
$city[$i] = $restaurants[$i]->get("City");
$objectID[$i] = $restaurants[$i]->getObjectID();
//echo '<input type="hidden" name="passRestaurant" value="' . $name[$i]. '" />'; // tried this, but it just messes up the format of the drop down
echo "<option>{$name[$i]} -" . " {$city[$i]}</option>";
}
echo '</select><br><br><input type="submit" name="submit" value="Next" />
</form>';
}
This prints the value that was selected, but I also want to print the $objectID[$i] at the same $i value:
if(isset($_POST['submit'])){
$selected_val = $_POST['Restaurant']; // Storing Selected Value In Variable
echo "You have selected :" .$selected_val; // Displaying Selected Value
}
why you just put $objectID[$i] in
echo "<option value=\"{$objectID[$i]}\">{$name[$i]} - {$city[$i]}</option>";
so you can get all the properties of Restaurant with $objectID

How do I get values from a table out of a foreach loop?

What I'm doing is trying to set up a page where users can see their created tools and delete them whenever they want. I'm querying three different tables and putting the results into an array. Once those values are in an array, a foreach loop goes through and populates a table with all the information in a table, like so:
$counter = 1;
echo '<table>'
foreach ($recent_saved_tools as $key => $value) {
echo '<tr name="item'.$counter.'">';
echo '<td>';
echo '<input type="hidden" name="tablename" value="'.$value['table'].'" />';
echo '<input type="hidden" name="tabledelete" value="'.$value['delete'].'" />';
echo '<input type="hidden" name="tableidfield" value="'.$value['idfield'].'" />';
echo '<input type="hidden" name="tableid" value="'.$value['id'].'" />';
//code to display the tool name and link
echo '<a style="text-decoration:none;" href="'.WEBSITE.'tools/'.$value['URL'].'?saved_data_id='.$value['id'].'">'.$value['display'].'</a><br />';
echo date("m/d/Y H:i:s", $key).'<br />';
echo '</td><td>';
//code to display the delete button
echo ' <input class="cssformbutton bluebutton" type="button" name="delete" id="deletebtn'.$counter.'" value="Delete" /><br /><br /><br /><br /></td>';
$counter ++;
}
echo '</table>';
The problem is whenever I run the SQL query, no matter what button I click it always takes the values from the last table row. I know it has something to do with the way they're named (multiple elements have the same name) but I'm at a loss on how to fix this. Any help would be appreciated.
Here's the query I'm using to delete the item:
$query = 'UPDATE '.$value['table'].' SET '.$value['delete'].' = 1 WHERE '.$value['idfield'].' = '.$value['id'];
$sql->query($query);
EDIT: added delete code
Every row has some inputs which are posted to the server. They have the same names - for every row. You could change it like this:
echo '<input type="hidden" name="tablename'.$counter.'" value="'.$value['table'].'" />';
Then you can use $_POST['tablename'.$rownr] in your delete code.
Doesn't look like you're closing the anywhere...
What results return from the query?
What output are you expecting?
try making it a for loop in stead and adding the variable to the end.
$array;
$counter = count($array);
echo '<table>'
for($i = 0; $i < $counter - 1; $i++) {
echo '<tr name="item'.$i.'">';
echo '<td>';
echo '<input type="hidden" name="tablename" value="'.$value['table']. $i'" />';
echo '<input type="hidden" name="tabledelete" value="'.$value['delete']. $i'" />';
echo '<input type="hidden" name="tableidfield" value="'.$value['idfield']. $i'" />';
echo '<input type="hidden" name="tableid" value="'.$value['id'].'" />';
//code to display the tool name and link
echo '<a style="text-decoration:none;" href="'.WEBSITE.'tools/'.$value['URL'].'?saved_data_id='.$value['id'].'">'.$value['display'].'</a><br />';
echo date("m/d/Y H:i:s", $key).'<br />';
echo '</td><td>';
//code to display the delete button
echo ' <input class="cssformbutton bluebutton" type="button" name="delete" id="deletebtn'.$counter.'" value="Delete" /><br /><br /><br /><br /></td>';
}
echo '</table>';

Categories