I'm having trouble populating a dropdown list from a database and then updating the selected item on a button click. What I'm trying to have is that when you pick Option B in the dropdown, it'll update that option on the click of a submit button.
I can get the dropdown box to populate fine, but when clicking the button it won't update correctly. I'm learning as I go, any pointers would be appreciated.
<form id='filter' name='filter' method='post' action=''>
<?php
$getIssuedVouchers2 = "SELECT * FROM vouchercodes WHERE status = 'Active'";
$issuedVouchersResult2 = mysql_query($getIssuedVouchers);
?>
<select>
<?php
while ($ivSelectRow = mysql_fetch_array($issuedVouchersResult2)) {
echo "<option name='updatestatus'>" . $ivSelectRow['vouchId'] . "</option>";
}
?>
</select>
<INPUT TYPE="Submit" VALUE="Update the Record" NAME="Submit" />
<?php
if(isset($_POST['Submit'])) { //if the submit button is clicked
$updatingQuery = "UPDATE vouchercodes SET status='Expired' WHERE vouchId = '".$ivSelectRow['vouchId']."' ";
mysql_query($updatingQuery) or die("Cannot update");//update or error
}
?>
</form>
PHP is a server side language. It runs once when you request the page, and after it is done it serves the page to you. It does not run until you do another page request, which PHP can't do because that's a client side action.
What you are looking for is Javascript and Ajax. They are client side languages. I'd recommend using Jquery for this, it's pretty easy to use once you get the hang of it. It makes it a lot less awful than standard javascript.
If you aren't wanting to avoid a page reload (submit -> handler -> page reload), I can cook up an answer for you for that. Maybe.
Update from your comment:
You want to set the "selected" attribute, which makes that option selected on page load, correct? e.g. pick the second item in the dropdown instead of the first.
You need to use the selected attribute on your option tag. That makes it selected.
Here's an example I use on one of my sites.
<select data-wavenum='<?=$i;?>' id="enemy<?=$i;?>" name="enemy<?=$i;?>" class="enemylist">
<option value="assaulttrooper" <?=($enemy == 'assaulttrooper') ? "selected" : ""?>>Assault Trooper</option>
This prints out something like:
<option value="assaulttrooper" selected>Assault Trooper</option>
In this case, $enemy is my item that makes me print selected out which makes that option be selected.
In your case, this is what it would be. It's kind of ugly. I think I fixed some of your code, but without the DB backend I can't test.
while ($ivSelectRow = mysql_fetch_array($issuedVouchersResult2)) {
$selected = false;
if (isset($_POST['Submit'])) {
$selected = ($_POST['vouchId'] == $ivSelectRow['vouchId']);
}
echo "<option name=".$ivSelectRow['vouchId']." ".($selected) ? "selected" : "".">" . $ivSelectRow['vouchId'] . "</option>";
}
Please be aware that I could change the option name or send a POST that would cause you to expire a value, or delete your entire table as your data is not sanitized.
Related
I want to create a dropdown list in a form and be able to submit/process it without pressing the submit button. I have
$cquery = 'SELECT * FROM tcat ORDER BY id ASC';
$cresult = mysql_query($cquery, $connection);
if(!$cresult){echo 'no result' . mysql_error();}
while($crow = mysql_fetch_array($cresult))
{echo $crow['cat'] . '</option><option>';}
?>
I would like to know if there is a way to make the default that is shown a different value aside the first or the last
even simpler, this should work too!
<select onchange="submit();">
<options ... >
</select>
To submit a form without having the user press a submit button, you can use JavaScript:
document.getElementById("form_id").submit();
To set a default selected option, you can do this:
<option selected="selected">Category Name</option>
Note that PHP will not auto-submit a form for you as it is a server-side language.
You have to use html and javascript and change your script to generate them accordingly:
<select name="aName" onChange="document.getElementById('yourFormId').submit();">
...
</select>
Thanking you for taking the time to look at this question.
The premise of the situation is that I have a "website" written in PHP and HTML that displays items from my database named "Spreadsheet." There are six columns, and over 4000+ rows of data. The columns are "accountID", "accountName", "website", "rating", "imageURL", "comments." The column "rating" in the website is a drop down list.
Currently, everything works well, but I have do questions:
How do I, with PHP, have data submitted to the database upon clicking on an option (such as "Very Bad") in the drop down list? At the moment, it requires the user to click a "submit" button, which refreshes the page entirely, losing their position. Is it possible to have it submit silently (without refreshing)
Second question has to do with the drop-down list again. How do you have the drop-down list display what's in the database? For example, if rating is "Very Bad" in the database, the drop-down list reflects that, and not what the first element is.
Below is my code.
". $row['website']."<br />
<Form Name =\"rating\" Method =\"POST\" ACTION =\"\" />
<input type = \"hidden\" name=accountID value=" . $row['accountID'] . ">
<select name=\"rating\">
<option value=\"\"></option>
<option value=\"Very Bad\">Very Bad</option>
<option value=\"Bad\">Bad</option>
<option value=\"Average\">Average</option>
<option value=\"Above Average\">Above Average</option>
</select>
<INPUT TYPE =\"Submit\" Name =\"formSubmit\" VALUE =\"Submit\">
if (isset($_POST['formSubmit'])){
$rating = $_POST['rating'];
$accountID = $_POST['accountID'];
var_dump($rating);
var_dump($accountID);
if(!mysql_query("UPDATE Spreadsheet SET rating='$rating' WHERE accountID='$accountID'")) {echo 1;}
}
mysql_close();
?>
Thanks so much! This question has been bothering me for a bit. I have tried many Google attempts, but I could not find an answer as specific as I am asking. Thank you so much.
Answer to #1:
You can use Javascript/AJAX to accomplish submitting the form without actually pressing submit. There are various javascript libraries that can help you accomplish this a lot easier than bare bones Javascript, namely jQuery ( http://jquery.com/ ). It's not a very complicated task but you will need to learn some basic Javascript and how to use jQuery. The essential flow of things would be when the form changes, submit an AJAX request to submit the form. You will need a second script to take the incoming AJAX request and do the save. Try search engines for some basic jQuery tutorials, and once you have a basic grip, something like "ajax submit on form change jquery" will get you started.
Answer to #2:
Something like this (please see my notes...)
echo '<select name="rating" id="rating">';
$q = mysql_query("SELECT `option_name` FROM `options`");
while($row = mysql_fetch_assoc($q)) {
echo '<option value="' . $row['option_name'] . '">' . $row['option_name'] . '</option>';
}
echo '</select>';
If you would like the select preselected, that's pretty easy too! Taking from the last example:
$pre_selected = "Very Bad";
echo '<select name="rating" id="rating">';
$q = mysql_query("SELECT `option_name` FROM `options`");
while($row = mysql_fetch_assoc($q)) {
echo '<option value="' . $row['option_name'] . '"';
if($row['option_name'] == $pre_selected) {
echo ' selected="selected"';
}
echo '>' . $row['option_name'] . '</option>';
}
echo '</select>';
But this is the part I'd like to point a few things out:
Don't use the old mySQL library like you are using and my examples are using. Please, use PDO, or at least mySQLi. The functions you are using are deprecated, and may not be available in PHP for much longer.
Please, escape your data properly. Search for "SQL Injection" and you will find a massive amount of information about how your code is very insecure (your UPDATE, specifically) because you did not escape the values.
Just a heads up, when/if you use jQuery, you're going to need to use id="foo" in addition to name="foo".
For the first question you can look at ajax onchange event. Basically when you change select value you fill call function that can call php file to insert data in db.
For the second question you check the DB for selected value and if it matches option value or text you set it to selected
<select name=\"rating\">
<option value=\"\"></option>
<option value=\"Very Bad\">Very Bad</option>
<option value=\"Bad\">Bad</option>
<option value=\"Average\">Average</option>
<option value=\"Above Average\"
<?php if($someValueFromDb=='Above Average'){
echo 'selected=selected';}?>
>Above Average</option>
</select>
I have a check box list which I fill it with data from my table.Here is the code:
<?php
mysql_connect("localhost","root","");
mysql_select_db("erp");
$a="Select * from magazine";
$b=mysql_query($a);
$c=mysql_fetch_array($b);
while($c=mysql_fetch_array($b))
{
print '<input type="checkbox"/>'.$c['den_mag'];
echo "</br>";
}
if(isset($_POST['den_mag']))
{
echo "aaaa";
}
?>
It's a simple query and for each data just show it with a checkbox.Now what I want is when I press a checkbox the value of that checkbox to be shown in a table.So if I have check1 with value a , check2 with value b and I check check1 the value a to be outputted to a table row.How can I achieve that? how cand I get which checkbox is checked?
A few notes:
Try to avoid using SELECT * queries. Select the fields you are going to use:
$sql= '
SELECT
id,
den_mag
FROM
magazine
';
Use better variable names. $a and $c make your code harder to follow for others, and for yourself when you come back at a later time. Use more descriptive variable names like $query_object and $row. Your code should read almost like an essay describing what you're doing.
In your form, use an array of elements. By giving the input a name like selected_magazines[], you will end up with an array in your post data, which is what you want -- multiple selections
Use the row ID as the value of the checkbox element. Your array in POST will then be a list of all the IDs that the user selected
Separate your logic from your HTML generation. The top portion of your script should take care of all logic and decisions. At the bottom, output your HTML and avoid making logical decisions. It makes for a script that is easier to follow and maintain, as well as debug.
Here is a sample script incorporating these ideas with the details you've given:
<?php
// FILE: myfile.php
mysql_connect("localhost","root","");
mysql_select_db("erp");
if(isset($_POST['selected_magazine'])) {
// $_POST['selected_magazine'] will contain selected IDs
print 'You selected: ';
print '<ul><li>'.implode($_POST['selected_magazine'], '</li><li>').'</li></ul>';
die();
}
$sql= '
SELECT
`id`,
`den_mag`
FROM
`magazine`
';
$query_object=mysql_query($sql);
$checkboxes = array();
while($row = mysql_fetch_array($query_object)) {
$checkboxes[] = '<input name="selected_magazine[]" value="'.$row['id'].'" type="checkbox" /> '.$row['den_mag'];
}
?>
<form action="myfile.php" method="post">
<?php print implode('<br>', $checkboxes); ?>
<input type="submit" value="Submit" />
</form>
<input name="test" type="checkbox" />
<?php
if(isset($_REQUEST['test'])){
// selected
}
?>
When you give input-type elements (input, textarea, select, button) a name attribute (like I did), the browser will submit the state/value of the element to the server (if the containing form has been submitted).
In case of checkboxes, you don't really need to check the value, but just that it exists. If the checkbox is not selected, it won't be set.
Also, you need to understand the client-server flow. PHP can't check for something if the client does not send it.
And finally, someone mentioned jQuery. jQuery is plain javascript with perhaps some added sugar. But the point is, you could in theory change stuff with jQuery so that it gets (or doesn't get) submitted with the request. For example, you could get jQuery to destroy the checkbox before the form is submitted (the checkbox won't be sent in this case).
Here you go :
<html>
<input name="test" value="true" type="checkbox" />
</html>
<?php
$Checkbox1 = "{$_POST['test']}";
if($Checkbox1 == 'true'){
// yes, it is checked
}
?>
I have written the following code in PHP to generate two dropdown boxes on the same page.
The first dropdown box gets value from a MySQL table. This dropdpwn box contains some UserIDs. The second dropdown box contains some dates which should be based on the UserID that is selected in the first dropdown box. I have filled the 2nd dropdown box with all the dates in the MySQL table, but, it should be filtered by the UserID which is selected on the first dropdown box.
Just to inform, with these two values from these two dropdown boxes in this PHP page, I have posted them by pressing the submit button to another PHP page to process some other work.
I would appreciate if you can help me to fill the second dropbox only based on the UserID selected on the first dropbox. Here is the code I have written to display and fill those dropdown boxes. Can you please inform me, what part of the code I should modify and I would appreciate if you can show me the modification code as well. I am a newbie in PHP, that's why I am asking for code level help.
My code:
<html>
<head>
<title>
Search Alert DB
</title>
<body>
<br />
<?php>
$con = mysql_connect("localhost","root","root"); // (host, user,pwd)
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("mysql", $con);
echo "<p> Search Alert database </p>";
echo "<br />";
$result = mysql_query("SELECT distinct(UserID) FROM tblAlertLogSpecificUsersDayStatusFinal_1");
$options="";
echo "<form action='Search_AlertDB_process.php' method='POST'>\n";
//echo "Please choose a user: ";
echo "Please choose a user: <select name = userid>";
echo "<option>-Select-";
while ($row = mysql_fetch_array($result))
{
$userid=$row["UserID"];
$options ="<option value = \"$userid\">$userid </option>";
echo "$options";
}
echo "</select>";
echo "<br />";
echo "<br />";
$dayresult = mysql_query("SELECT distinct(Occurred_date) FROM tblAlertLogSpecificUsersDayStatusFinal_1");
$dayoptions="";
echo "Please pick a date:<select name = day>";
echo "<option>-Select-";
while ($row=mysql_fetch_array($dayresult)) {
$day=$row["Occurred_date"];
$dayoptions ="<option value = \"$day\">$day </option>";
echo "$dayoptions";
//$options.="<OPTION VALUE=\"$id\">".$day;
}
echo "</select>";
echo "<br />";
mysql_close($con);
?>
<br />
<input type="submit" name="Submit" value="Search" /> <br /> <br />
</form>
</body>
</html>
You'll need 3 things
Initial page with select fields
The first select field is pre-populated with user ids
The second field contains no options and is disabled
A separate endpoint/page that takes a user id as a parameter to return relevant dates
It should probably return JSON/XML (or something similar), or you could return the dates pre-rendered in <option /> tags (shouldn't really do this, but it would be quicker to hack this together)
Javascript callback triggered when an option in the first dropdown is selected. The callback should send an AJAX request to the separate endpoint and populate the second dropdown with the result.
It would have probably been easier for me to write it all out for you than [try] to explain it, but that's not really the point. Just trying to set this all up (all be it; relatively simple) will teach you a whole load of things about Javascript, AJAX and web services.
If you choose to return JSON/XML from your web service (the separate endpoint/page), and hopefully you will, you might also start to see the benefit of separating logic from presentation, which will make the world of difference to both your understanding and delivery of code.
Well, we wont write the code for you. Otherwise you are going to be newbie for all your life :)
What you need here is called AJAX. The easiest way to implement it is probably jQuery ajax function. If you don't know jQuery - learn the basics, it shouldn't take more than an hour or so. It's worth it :)
I have two drop down lists.
Second one is populated based on value chosen in the first one. I'm using Double Combo Script Credit By JavaScript Kit to do that (I am very bad with javascript).
I use this to filter results from my Mysql database.
The problem is that when user applies filter i want him to see what he applied (when page refreshes or user goes to other page) - those values should be seen as selected in both drop down lists. I can't figure out where i should place an event or something else.
I'm holding subcategory values from the second drop down list in php session :
if (isset($_SESSION['subcat']) && !isset($_GET['subcat'])){
$color= $_SESSION['subcat'];
}
elseif (!isset($_SESSION['subcat']) && isset($_GET['subcat']))
{
$_SESSION['subcat'] = mysql_real_escape_string($_GET['subcat']);
$color= $_SESSION['subcat'];
}
elseif (isset($_SESSION['subcat']) && isset($_GET['subcat'])){
unset($_SESSION['subcat']);
$_SESSION['subcat'] = mysql_real_escape_string($_GET['subcat']);
$color= $_SESSION['subcat'];
}
else {
$color= "";
};
I can echo selected in first drop down list, based on session value and that works, but a second one drop down list is not generated when page refreshes and i don't know where should i echo 'selected = "selected"' or maybe everything can be done only with javascript? Please help.
The code:
<div class="filter">
<form method="get" name="doublecombo" action="" id="filterform" >
<select name="example" id="exampl" size="1" onChange="redirect(this.options.selectedIndex)">
<option>All kinds</option>
<option>Women</option>
<option>Men</option>
</select>
<select name="subcat" size="1" id="subcategory">
<option value="lists.php">All colors</option>
</select>
<input type="button" name="test" value="Filter" onClick="go()">
</p>
<script>
<!--
/*
Double Combo Script Credit
By JavaScript Kit (www.javascriptkit.com)
Over 200+ free JavaScripts here!
*/
var groups=document.doublecombo.example.options.length
var group=new Array(groups)
for (i=0; i<groups; i++)
group[i]=new Array()
group[0][0]=new Option("All colors","list.php")
group[1][0]=new Option("Pink","list.php?subcat=1 ")
group[1][1]=new Option("White","list.php?subcat=2")
group[1][2]=new Option("Green","list.php?subcat=3")
group[2][0]=new Option("Black","list.php?subcat=12")
group[2][1]=new Option("Blue","list.php?subcat=13")
group[2][2]=new Option("Grey","list.php?subcat=14")
group[2][3]=new Option("Brown","list.php?subcat=15")
var temp=document.doublecombo.subcat
function redirect(x){
for (m=temp.options.length-1;m>0;m--)
temp.options[m]=null
for (i=0;i<group[x].length;i++){
temp.options[i]=new Option(group[x][i].text,group[x][i].value)
}
temp.options[0].selected=true
}
function go(){
location=temp.options[temp.selectedIndex].value
}
//-->
</script>
</form></div>
you could set a cookie to hold the selected value, so if the user selects there choice and refreshes, you would then check if the cookie exists and then populate the menus accordingly.
Update:
This will store the selected values and repopulate the select menus if the user refreshes the page.
First select added onkeup:
<select name="example" id="exampl" size="1" onchange="redirect(this.options.selectedIndex)" onkeyup="redirect(this.options.selectedIndex)">
for the second select and as follows to check for changes
<select name="subcat" size="1" id="subcategory" onchange="checks(this)" onkeyup="checks(this)">
Now find the Line temp.options[0].selected=true and add this directaly below
createCookie("selected_option_1", x, 0);
if(x==0){
eraseCookie("selected_option_2");
}
then add these two new function say at the bottom of your script block
// checks if the Second Select has changed
function checks(oWhich){
createCookie("selected_option_2", oWhich.selectedIndex, 0);
}
// repopulate the options base on selection thats saved in the cookies
onload = function(){
if(readCookie("selected_option_1") != null) {
redirect(document.doublecombo.example.options.selectedIndex = readCookie("selected_option_1"));
if(readCookie("selected_option_2") != null) {
document.doublecombo.subcat.options.selectedIndex = readCookie("selected_option_2");
}
}
}
Finaly for these functions/scrip to work you will need
// The cookie script im using for the functions is located below include this and you chould ok. http://www.quirksmode.org/js/cookies.html#script
Now once the form has been submitted you GET the selected values as usual, and the REPOPULATE the menu, once you done with the cookie you could remove them.
If it's jQuery you are using you can try a short PHP tag on the page like this:
jQuery('#MyDropDown').val('<?php echo $_SESSION['MyStoredValue']; ?>');
If you are not using jQuery but straight JavaScript this would have the same effect:
document.getElementById("MyDropDown").value = '<?php echo $_SESSION['MyStoredValue']; ?>'