Keep selections in php generated form after submit (POST) - php

I'm currently using php to populate a form with selections from a database. The user chooses options in a select style form and submits this, which updates a summary of the selections below the form before a second submit button is used to complete the interaction.
My issue is that every time a user uses the first submit, the selections that were there previously do not stick. They have to go through the whole form again.
Is there anyway to keep these selections present without resorting to php if statements? There are a ton of options so it would be a pain to use php for each one. Also, form is being submitted via POST.
Sample from form:
<?php
// GRAB DATA
$result = mysql_query("SELECT * FROM special2 WHERE cat = 'COLOR' ORDER BY cat")
or die(mysql_error());
echo "<div id='color'><select id='color' name='product_color'>";
while($row = mysql_fetch_array( $result )) {
$name= $row["name"];
$cat= $row["cat"];
$price= $row["price"];
echo "<option value='";echo $name;echo"'>";echo $name;echo" ($$price)</option>";}
echo "</select>";
echo "<input type='hidden' name='amount_color' value='";echo $price;echo"'></div>";
?>
I tried using this js snippet to repopulate the selections, but it does not seem to work properly...
<script type="text/javascript">document.getElementById('color').value = "<?php echo $_GET['proudct_cpu'];?>";</script>
This does not seem to work. Any suggestions other than php if statements?
Thanks!
edit: This is basically the form set up I'm using, though I've shortened it significantly because the actual implementation is quite long.
// Make a MySQL Connection
<?php mysql_connect("localhost", "kp_dbl", "mastermaster") or die(mysql_error());
mysql_select_db("kp_db") or die(mysql_error());
?>
<br />
<form action="build22.php" method="post">
<input type="hidden" name="data" value="1" />
<br />
<br />
<?php
// GRAB DATA
$result = mysql_query("SELECT * FROM special2 WHERE cat = 'color' ORDER BY cat")
or die(mysql_error());
echo "<div id='color'><select id='color' name='product_color'>";
while($row = mysql_fetch_array( $result )) {
$name= $row["name"];
$cat= $row["cat"];
$price= $row["price"];
echo "<option value='";echo $name;echo"'>";echo $name;echo" ($$price)</option>";}
echo "</select>";
echo "<input type='hidden' name='amount_color' value='";echo $price;echo"'></div>";
?>
<input type="submit" value="Update Configuration">
</form>
The selections from the form above get echoed after submission to provide the user with an update as such:
<div id="config" style="background-color:#FFF; font-size:12px; line-height:22px;">
<h1>Current Configuration:</h1>
<?php echo "<strong>Color:</strong>&nbsp&nbsp&nbsp&nbsp";echo $_POST['product_color']; ?>
</div>

I assume you're storing the user's selections in a separate table. If that's the case, you'll need to add some logic to determine if you should display the form values or what's already been stored.
<?php
// form was not submitted and a config id was passed to the page
if (true === empty($_POST) && true === isset($_GET['config_id']))
{
// make sure to properly sanitize the user-input!
$rs = mysql_query("select * from saved_configuration where config_id={$_GET['config_id']}"); // make sure to properly sanitize the user-input!
$_POST = mysql_fetch_array($rs,MYSQL_ASSOC); // assuming a single row for simplicity. Storing in _POST for easy display later
}
?>
<div id="config" style="background-color:#FFF; font-size:12px; line-height:22px;">
<h1>Current Configuration:</h1>
<?php echo "<strong>Color:</strong>&nbsp&nbsp&nbsp&nbsp";echo $_POST['product_color']; ?>
</div>
So after storing the user's selections in the database, you can redirect them to the page with the new config_id in the URL to load the saved values. If you're not storing the selected values in a table, you can do something similar with cookies/sessions.

echo the variables into the value tag of the form elements. If you post all your code I'm sure I can help you.
UPDATE
ah, so they are dropdown lists that you need to remember what was selected? Apologies, I read your post in a rush yesterday and thought it was a form with text inputs.
I just did a similar thing myself but without trying your code let me see if I can help.
Basically what you need to do is set one value in the dropdown to selected="selected"
When I had to do this I had my dropdown values in an array like so:
$options = array( "stack", "overflow", "some", "random", "words");
// then you will take your GET variable:
$key = array_search($_GET['variablename'], $options);
// so this is saying find the index in the array of the value I just told you
// then you can set the value of the dropdown to this index of the array:
$selectedoption = $options[$key];
This is where it might be confusing as my code is different so if you want to use it you will probably need to restructure a bit
I have a doSelect function to which I pass the following parameters:
// what we are passing is: name of select, size, the array of values to use and the
// value we want to use as the default selected value
doSelect("select_name", 1, $options, $selectedoption, "");
// these are the two functions I have:
// this one just processes each value in the array as a select option which is either
// the selected value or just a 'normal' select value
FUNCTION doOptions($options, $selected)
{
foreach ($options as $option)
{
if ($option == $selected)
echo ("<option title=\"$title\" id=\"$value\" selected>$option</option>\n");
else
echo ("<option title=\"$title\" id=\"$value\">$option</option>\n");
}
}
// this is the function that controls everything - it takes your parameters and calls
// the above function
FUNCTION doSelect($name, $size, $options, $selected, $extra)
{
echo("<select class=\"\" id=\"$name\" name=\"$name\" size=\"$size\" $extra>\n");
doOptions($options, $selected);
echo("</select>\n");
}
I know that's a lot of new code that's been threw at you but if you can get your select values from the db into the array then everything else should fall nicely into place.
The only thing I would add, is at the start where we call doSelect, I would put that in an if statement because you don't want to set something as selected which hasn't been set:
if (isset($_GET['variable']))
{
$key = array_search($_GET['variablename'], $options);
$selectedoption = $options[$key];
doSelect("select_name", 1, $options, $selectedoption, "");
}
else
{
doSelect("select_name", 1, $options, "", "");
}
I hope that helps!

Related

PHP/MySQL Auto select option based on previous page

I have a music database with a PHP front end where you can add/edit/delete artists, albums, tracks using the web client. The last real problem I have is getting a select box to automatically select an option I pass to the page.
Example:
On a page called 'createCD.php' I have this code:
echo "<td><a href=\"editCD.php?cdTitle=".rawurlencode($row['cdTitle'])."&cdID=$row[cdID]&artID=$row[artID]&cdGenre=".rawurlencode($row['cdGenre'])."&cdPrice=$row[cdPrice]\" </a>Edit</td>";`
This is used as a link to the next page, and collects all the information about an album in the database and sends in to a page called 'editCD.php'.
Now on this page, all the information is used to fill out the webpage as shown here (there is more but for the purposes of this post, only the first select box matters):
Artist Name:
<!-- dropdown with artist name -->
<?php
echo '<select name= "artID" id="artID">';
while ($row = mysqli_fetch_assoc($result)){
echo '<option value="'.$row['artID'].'">'.$row['artName'].'</option>';
}
echo '</select>';
?>
<p>
Album Title:
<input id="cdTitle" type="text" name="cdTitle" value ="<?php echo htmlspecialchars($cdTitle); ?>" />
</p>
What I would like is for the "selected" option for 'artID' to be the value that is passed to the page. Using the associative array, I was able to display the 'artName' associated with the 'artID'. Currently, all the information about the album appears correctly apart from the 'artName' and it defaults to the first value. This is a problem as if a user simply clicks "Update" it will update the name to the default name, therefore changing the database entry by accident.
I know I need to be using
<option selected ...>
but I'm not sure on the syntax to use.
<?php
$artID = $_GET['artID']; // get the artID from the URL, you should do data validation
echo '<select name= "artID" id="artID">';
while ($row = mysqli_fetch_assoc($result)){
echo '<option value="'.$row['artID'].'"';
if ($artID == $row['artID']) echo ' selected'; // pre-select if $artID is the current artID
echo '>'.$row['artName'].'</option>';
}
echo '</select>';
?>
$artId = $_GET['artID'];
while ($row = mysqli_fetch_assoc($result)) {
$selected = $artId == $row['artID'] ? 'selected' : '';
echo '<option value="'.$row['artID'].'" '.$selected.'>'.$row['artName'].'</option>';
}
First you get the id via $_GET['artID']. (In a real scenario use intval or something to prevent sql injection)
Then check in the loop if the id from database is the same as the id from GET and when it is print "selected, else nothing.

Posting a value from Dropdown List from PHP div page

I'm having an issue in passing a value from a dropdown list that is in a separate PHP file that is being used by jquery.
I ended up getting the values from the dropdown list that isn't posting correctly by using jquery based on the value selected in the first dropdown list. The dropdown list in question is populating correctly, but with the way I have it setup I cannot post the value to the submit PHP page.
I'm pretty sure it has to do with the way I have it setup; however, I'm very new to jquery and was looking for some guidance.
The main PHP Page (the small areas in question)
<select name="department_list" id="department_list" onchange="$('#singleUser').load('get_users.php?nid='+this.value);">
...
<div id="singleUser" class="singleUser">
</div>
The PHP page (get_users) used to fill the values (only the area in question)
echo '<p style="text-align:center">';
echo "
<br />
Select a person to receive the form
<br />";
echo "<select id='userSelect' class='userSelect'>";
if ($id == '50') {
echo "<option value='Done'>Done</option>";
echo "</select>";
}else {
echo "<option value='none'>Select user</option>";
try {
$db = new PDO("mysql:host=$hostname;dbname=$dbname", $username, $password);
$stmt = $db->prepare("SELECT dm.empid AS empid, u.name AS name FROM mytable dm
JOIN mytable2 u ON dm.empid = u.id
WHERE dm.deptid = :id
ORDER BY u.name");
$stmt->bindParam(':id', $id);
$stmt->execute();
while ($r = $stmt->fetch()) {
$empid = $r['empid'];
$userName = $r['name'];
echo "<option value='".$empid."'>".$userName."</option>";
}
echo "</select>";
echo "</p>";
$db = null;
}
catch (PDOException $ex) {
echo "An Error occurred!";
}
}//end else
In the submit page:
if(isset($_POST['userSelect'])){
$givenID = $_POST['userSelect'];
//the rest of my code
I do have the div code above within the form tags and have method="post". All of my other inputs post correctly, so I'm thinking it has to do with the way I have only the div tags within the main page. Again, I'm pretty new to all of this so any ideas or changes that I should make so it posts correctly would be greatly appreciated.
You forgot the name of the select when you write it with php:
change this:
echo "<select id='userSelect' class='userSelect'>";
to
echo "<select id='userSelect' name='userSelect' class='userSelect'>";
i think the error is in the PHP file generating the user select it is missing the name attribute name="userSelect"
echo "<select id='userSelect' class='userSelect'>";
it should be
echo '<select id="userSelect" name="userSelect" class="userSelect">';
every form element with the name attribute gets posted with its value. if you do not enter the name attribute, the value can not be retrieved from the $_POST array. Also have in mind that disabled form inputs also do not get posted.
Edited the PHP quotes. Use Single qutes everyt time you do not need to insert PHP variable into the string. It is ~9 times faster than double quotes ;)

form with array of checkboxes send incomplete data

I try to pass a form which contains other forms (same inside forms, dynamic) , but I have checked that the data which are sent to the 'script handler' (php) are incomplete data. I think somewhere buffer is overwriting or something. Here is the code :
<?php
if(isset($_POST['submit_num']))
{
$number=$_POST['sky'];
if($number== 0)
{
header('Location: /ceid_coffee/user_order_form.php');
}
else
{
$_SESSION['number'] = $number;
echo '<form action="user_order_form.php" method="POST">';
for($i=0;$i<$number;$i++)
{
$item = $_SESSION['item'];
echo $item;
$rec_query = "SELECT * FROM ylika";
$rec_result= mysql_query($rec_query) or die("my eroors");
while($row_rec = mysql_fetch_array($rec_result))
{
echo '<br>';
echo '<input type="checkbox" name="yliko[][$i]" value='.$row_rec['onoma'].'> '.$row_rec['onoma'].'';//<~~~~this line is form's data
}
echo '<br>';
}
echo '<input type="submit" name="submit" value="FINAL_ORDER">';
echo '</form>';
}
}
?>
And this is the handling script:
<?php
if (isset($_POST['submit']))
{
$number= $_SESSION['number'];
$item = $_SESSION['item'];
$max_id = "SELECT MAX(id_order) FROM id_of_orders";
$x=mysql_query($max_id) or die("my eroors");
$id= mysql_fetch_array($x);
$xyz = $id['MAX(id_order)'];
for($i=0;$i<$number;$i++)
{
$temp = $_POST['yliko'][$i]; // <~~~~ this line is the form's data
$temp2 = implode("," , $temp);
$inserts = ("INSERT INTO orders (order_id,product,ulika) VALUES ('$xyz' , '$item','$temp2')");
$inc_prod=("UPDATE proion SET Counter = Counter + 1 WHERE proion.onomasia='$item'");
mysql_query($inserts) or die(mysql_error());
mysql_query($inc_prod) or die(mysql_error());
}
}
?>
This line here contains the data of each form , but i have echo them ($temp2) and i saw that they are incomplete.
$temp = $_POST['yliko'][$i];
If i select more than 1 checkbox for each item ($i) I get only one value from the checkboxes into the sql.
Do you see if I miss something ?
Ok i found the error. I replace this row :
echo '<input type="checkbox" name="yliko[][$i]" value='.$row_rec['onoma'].'> '.$row_rec['onoma'].'';//<~~~~this line is form's data
with this row :
echo '<input type="checkbox" name="yliko['.$i.'][]" value='.$row_rec['onoma'].'> '.$row_rec['onoma'].'';
I do not know how (i'm new to php) but it worked.
You will only get one value for each form because you are assigning the value of $i to each one:
echo '<input type="checkbox" name="yliko[][$i]" value='. etc.
is your problem line.
Have a look at the HTML that your code produces (ctrl-u in most browsers) and you will see why you get the wrong answer. All your checkboxes need to have unique names.
I would do it by assigning each checkbox a name that relates to the line in the database from which they are drawn eg:
name="checkbox_"'.$row['ylikaprimarykey']."etc.
This will get you up and running fairly quickly. For what it is worth, the ids of your table keys can give attackers information about your site so it is best practice to obfuscate them in some way. There are a number of excellent classes available free on the net that will do this for you.
If you really need to deal with what would have been in each form as a separate chunk of data, you can easily change the checkbox names vis:
name="checkbox_$formnumber_$obfuscatedkeynumber"
then loop through them with nested loops in your handling page.

How to retrieve imploded array from a cell in an MySQL database through PHP

Thanks for taking the time to look at this question.
Currently, I have a piece of code that creates four checkboxes labeled as "Luxury, Brand, Retailer," and "B2B." I have looked into a number of PHP methods to create checkboxes, and I felt the implode() function was the most simple and suitable for my job. I have looked into a number of tutorials to create the implosions, however, they did not fit my criteria, as I would like the database values be reflected in the front-end. Currently in my database, the implode() works, therefore (for example), if I check "Luxury", "Brand", "Retailer", and press the "Submit" button, the three items "Luxury, Brand, Retailer" will be in that specified cell. It looks like my code works in the back-end, but these are my issues:
I am not exactly sure (despite multiple Googles) how to retrieve those values stored in the single-cell array, and have it selected as "selected" (this would "check" the box in the front-end)
Could someone kindly take a look at my code below and let me know what seems to be missing/wrong/erroneous so I could attempt the revisions? Anything would be appreciated, thank you!
<?
if (isset($_POST['formSubmit2'])){
$category = mysql_real_escape_string(implode(',',$_POST['category']));
$accountID = $_POST['accountID'];
mysql_query("UPDATE Spreadsheet SET category='$category' WHERE accountID='$accountID'");
}
$query = mysql_query("SELECT * FROM Spreadsheet LIMIT $firstRow,$rpp");
while($row = mysql_fetch_array($query)){
// Begin Checkboxes
$values = array('Luxury','Brand','Retailer','B2B');
?>
<form name ="category" method ="POST" action ="" >
<?
echo "<input type = 'hidden' name = 'accountID' value = '" . $row['accountID'] . "' >";
for($i = 0; $i < count($values); $i++){
?>
<input type="checkbox" name="category[]" value="<?php echo $values[$i]; ?>" id="rbl_<? echo $i; ?>" <? if($row['category'] == $i) echo "checked=\"checked\""; ?>/>
<? echo $values[$i] ?><br>
<? } ?>
<input type ="Submit" name ="formSubmit2" value ="Submit" />
</form>
<? } ?>
The best approach i can recommend given what you have is to, explode the values out of the db giving you a new array of all the select fields. Then use in_array to compare the list you have with this new list in the loop. then flag the checkboxs as needed.

PHP - input type hidden to get id

i want when user select one student name to get the student id as a hidden input to use it in the next page , the problem is when i added this to my code it doesn't show all students list to select from , it shows only one student name ( the first one stored in the database ) m any ideas ? !
my code
$sql = "SELECT s.Sname, e.PID , s.SID
from student AS s
INNER JOIN evaluator AS e
WHERE (e.EID1 = '$id' AND s.PID = e.PID) OR (e.EID2 = '$id' AND s.PID = e.PID)
GROUP BY s.Sname ";
$result = mysql_query ($sql, $connection);
echo "<tr><th >Student Name <font size='4'></font></th>";
echo "<td><select id='Sname' name='Sname' >";
echo "<option value='' selected='selected'>--</option> ";
while( $row = mysql_fetch_array($result))
{
echo "<option value='$row[Sname]' >$row[Sname]</option> ";
echo " <input type ='hidden' name='SID' value='".$row['SID']."' >;
}
The problem is you are creating multiple <input> with name='SID' and the receiving page will probably only accept the first one. You need to create them as an array instead with []
echo " <input type ='hidden' name='SID[]' value='".$row['SID']."' ></option>";
//----------------------------------^^^^^^
In the receiving page, check the contents with var_dump($_POST['SID']). It will be an array and you can iterate it with a foreach().
I note that you are nesting <input> inside <option>s. That is probably not a good approach ( I don't think it is valid HTML). Instead, store all the SID in an array and loop twice to create your inputs.
$ids = array();
while( $row = mysql_fetch_array($result)) {
// First make an array of ids
$ids[] = $row;
}
Then loop over it twice, to build the select options, and the hidden inputs:
// <select> opened above...
// Inside the <select> tag already opened...
foreach ($ids as $id) {
echo "<option value='$id[Sname]' >$id[Sname]</option> ";
}
// Close the <select>
// </select>
// Then later, loop to build the hidden inputs in the array format
foreach ($ids as $id) {
echo " <input type ='hidden' name='SID[]' value='".$id['SID']."' >";
}
On the subject of valid HTML... I also see a stray closing </font> in there. <font> is deprecated, and instead you should be using CSS to define font properties.
Update after comments:
If you want to pass the SID along with the value (Sname) in the <option> then it is easiest to skip the hidden <input> entirely. Instead, pass both values in the <option value> attribute, separated by something like a |. In the PHP code that receives it, explode() them back into two values:
// In your original while loop:
// The value consists of both SID and Sname, separated by |
// Now, you have no need for the <input type='hidden' name='SID'> at all. Remove them.
echo "<option value='$row[SID]|$row[Sname]' >$row[Sname]</option> ";
// Then in the PHP script which receives the form values, explode() them:
// Both values come from the <select name='Sname'>
list($SID, $Sname) = explode("|", $_POST['Sname']);
// Now your variables $SID and $Sname hold the correct values
// If you need to reuse them, store into `$_SESSION
session_start();
$_SESSION['SID'] = $SID;
$_SESSION['Sname'] = $Sname;
// On other scripts, to read the values
session_start();
echo $_SESSION['SID'];
If you are unfamiliar with how to use $_SESSION, review the manual on basic usage. Long story short, you must call session_start() on each script that accesses $_SESSION, and you must do so before the script produces any output, including whitespace. This is the standard method of sharing data between scripts.

Categories