PHP combobox result after submit - php

i've tried many solutions from the website, but noone give me the result.
I have a combobox, and i insert data from mysql db
after pressing "submit button", the combobox refresh, but restart from first data and not from selected,
hereunder my code,
can someone help me?
$result = mysql_query("SELECT * FROM courier");
while($row = mysql_fetch_array($result))
{
echo "<option ". (($_POST['NAZIONE'] == $row["NAZIONE"]) ? 'selected ' : '') ."value=\"".$row["NAZIONE"]."\">".$row["NAZIONE"]."</option>";
}
echo'</select> <br> <input type="submit" value="Proceed">';
mysql_close($con);
?>

you can set selected value to $_SESSION variable and then you can get that selected value

Related

Pre Populating a PHP Dynamic Select Option with Stored Session Variable

Im scratching my head once again and need your help.
What I have is a form that submits to a second page, with sessions enabled, i am storing the name value 2 fields on the form and setting their value names in the session so that if a user returns to a page their Username will already be populated in the text field. I have this working ok ..
The second page i am storing
$_SESSION['captured_by'] = $_POST['captured_by'];
$_SESSION['prid'] = $_POST['prid'];
HOWEVER..
Where i am stuck is getting a select option that is populated from a query to have the same functionality, so that when a user returns to the page, the selected option which has been saved in the session will keep that selection in the box rather than having to select it again.
Here is what i have as follows:
Form Page:
This does work and does return the captured_by text when i return to the page
<fieldset><legend>Lesson Added By *</legend>
<p class="multiple">(Required - Logon ID)</p>
<input name="captured_by" maxlength="12" id="searchfield" type="text" value="<?php
if(isset($_SESSION['captured_by'])){print stripslashes($_SESSION['captured_by']);}
else{print " ";} ?>">
</fieldset>
The problem code is this
<select id="searchfield" name="prid">
<?php
$query = "SELECT project_name, project_id FROM ll_project ORDER BY project_name ASC;";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_assoc($result)) {
echo '<option value="'.$row['project_id'].'">'.$row['project_name'].' | '.$row['project_id'].'</option>';
}
?>
</select>
</fieldset>
I need to edit this last section so that it picks up the previously selected option value from the stored session value.
Hope someone can help?
Many Thanks.
Tazzy
Try this,
<select id="searchfield" name="prid">
<?php
$query = "SELECT project_name, project_id FROM ll_project ORDER BY project_name ASC;";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_assoc($result)) {
echo '<option value="'.$row['project_id'].'"'. ((isset($_SESSION['prid']) && !empty($_SESSION['prid']) && ($_SESSION['prid'] == $row['project_id'])) ? 'selected="selected"' : '') .'>'.$row['project_name'].' | '.$row['project_id'].'</option>';
}
?>
</select>
</fieldset>
You could simply use ajax when someone change the selection.
$('select#searchfield').change(function(){
$.ajax({
type: 'GET',
url: 'changeSession.php', // This is the url that will be requested
data: {prid: $('select#searchfield').val()},
success: function(html){
// nothing really happens because you simply update your session
},
dataType: 'html'
});
});
Then in changeSession.php
if(isset($_GET['projectId']{
$_SESSION['captured_by'] = $_POST['prid'];
}
That should do the job. You then add a condition when the form is generated and you add selected='selected' if $_SESSION['prid'] is not empty.

Grabbing a value from a SELECT box in PHP

I've got a drop down select box that grabs each relevant value from an SQL database in a loop.
I'm creating a form so that when the "Submit" button is pressed it redirects to a PHP file that carries out the INSERT SQL statement. However because the select options are coming from a loop I'm unsure of how to grab the right value when its selected as it just grabs the last value gained from the loop.
I'm pretty sure that the way I have done it is the wrong way to go
<?php
echo"<select name='ModuleTitle' id='ModuleTitle' style='width:100%;'>";
echo"<option>Select...</option>";
//3. Perform database query
$result = mysql_query("SELECT * FROM Module
ORDER BY `ModTitle` ASC;", $connection);
if(!$result){
die("Database query failed: " . mysql_error());
}
//4. Use Returned Data
while ($row5 = mysql_fetch_array($result)) {
$module = $row5[2];
echo "<option name='{$module}'>".$row5[2]."</option><br />";
}
echo"</select>";
echo "<a href='submitREQ.php?id={$module}'><img src='images/submit.jpg' height='27'></a>";
?>
Instead of using <a href you should use <input type="image" value="submit" src="images/submit.jpg" />
To grab the value after the form is submitted you should use: $ModuleTitle = $_POST['ModuleTitle']; or $_GET if the method is get.

Delete selected data in a checkbox

I'm making a website on which I have a set of data with checkbox. I need to delete multiple rows from database when I select multiple checkboxes. I don't know how to pass the id of the selected checkboxes to next page. Please help me.
Here is my code:
$select_qry="select * from data";
$result=mysql_query($select_qry);
$rows=mysql_num_rows($result);
if($rows>0)
{
?>
<form action="delete_submit.php" method="post">
<?php
for($i=0;$i<$rows;$i++)
{
$arr=mysql_fetch_assoc($result);
$id=$arr['id'];
$name=$arr['name'];
//echo $id;echo "<br>";echo $name;
?>
<input name="checkbox[]" type="checkbox" value="<?php echo $id;?>">
<?php
}
}
?>
How can I pass the selected checkboxes' id to the next page? Please help me.
Thanks
when form will be submitted then $_POST['checkbox'] will be set and contain the array of selected ids.
In your delete script
if(isset($_POST['checkbox']) && count($_POST['checkbox']) > 0){
$deleteIds = $_POST['checkbox']; // it will be an array
$sql = "DEFRE FROM tablename WHERE id in (".implode("," , $deleteIds).") ";
// run the query
}

Keep selections in php generated form after submit (POST)

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!

How to get value from Combo Box PHP?

I am using PHP 5 to create a query page for a MySQL database with 2 tables "students" and "teachers". I have created a combo box which can allow users to view and select the 2 tables from the combo box via a "submit" button after selecting from the combo box.
However the problem with the script is that I want to verify if the "submit" button works which I created a "echo.php" to echo out the value of the combo box and submit button. Overall the idea is to do a query like these steps:
1) User selects value from combo box "teacher" or "student".
2) User clicks submit button.
3) After clicking submit button, user is redirected to "echo.php"
4) "echo.php" should output/echo out either "teacher" or "student".
The codes for script:
<?php
include "db_connect.php";
{
?>
<td valign=top><strong>Name:</strong></td>
<td>
<?php
echo "<form name = \"queryEquipTypeForm\" method = \"post\" action
=\"select_table.php\">";
echo '<select name=\"table\">';
echo "<option size =30 selected>Select</option>";
$result = mysql_query("show tables");
if(!$result) trigger_error("Query Failed: ". mysql_error($db), E_USER_ERROR);
if(mysql_num_rows($result))
{
while($table_array = mysql_fetch_array($result))
{
echo "<option>$table_array[0]</option>";
}
echo '</select>';
echo '</form>';
if(!$_POST['submit'])
{
?>
<form method="post" action="select_table.php">
<input type="submit" name="submit" value="Submit">
</form>
<?php
}
else
{
echo '<script type="text/javascript">
alert("Redirecting you to echo.php page");
window.location="echo.php"</script>';
}
}
else
{
echo "<option>No Names Present</option>";
}
}
?>
</td>
The codes for "echo.php" :
<?php
include "select_table.php";
echo "data is : ".$_POST['table'];
?>
The output of echo.php would be exactly the same as "select_table.php" with the cobo box and the "data is: " without the "teachers" or "student" word as its being redirected to echo.php.
I'm not quite sure what exactly what you want to do, but as michaeltwofish already pointed out, redirecting to another page using javascript will make you lose the post data. Also you seem to echo two <form> elements when the select_table.php is called without post data, one with only a submit button, while your first form is missing the button.
Normally, you would want your php script to either output the form with the combobox where the user can select the table, or, if there was post data (meaning that the user selected a value), the results of the selection, kinda like the following:
<?php
if(isset($_POST['table'])) {
print "Selected element: " . $_POST['table'];
} else {
echo '<form method="post" action="select_table.php">';
echo '<select name="table">';
// here should be your SQL query and the combobox options generation
echo '</select>';
echo '<input type="submit" />';
echo '</form>';
}
?>
When the form is submitted, you redirect to echo.php, but that means you lose the POST data. You need to think carefully about the flow of your application, because what you have seems a bit confused.

Categories