I am new to php and web programming.
I am programming a website that collects essays. In the submission form, I want the date to be entered by 3 select dropdown forms (day-month-year). I used to add them in a text field and save them as strings in database. I added already hundreds of essays so I am not changing the type of data.
I did the following:
1- I made a dynamic dropdown using php:
function get_dropdown_options( $name, array $options, $selected=null ) {
$dropdown = '<select name="'.$name.'" id="'.$name.'">'."\n";
$selected = $selected;
foreach( $options as $key=>$option )
{
$select = $selected==$key ? ' selected' : null;
$dropdown .= '<option value="'.$key.'"'.$select.'>'.$option.'</option>'."\n";
}
$dropdown .= '</select>'."\n";
return $dropdown; }
2- then I made a function to show three dropdown menus for days, months and years.
function show_date_dropdown_row($name, $label, $option1, $option2, $option3, $value = "") {
echo "<tr class=\"".get_row_bg()."\" valign='top'>\n<td><p class=\"rowtitle\">".$label."</p></td>\n";
echo "<td><p>\n";
echo get_dropdown_options($name1, $option1, $value1).get_dropdown_options($name2, $option2, $value2).get_dropdown_options($name3, $option3, $value3);
return $name = $name1." - ".$name2." - ".$name3;
}
3- in the submission form page, I put the following code:
show_date_dropdown_row("release_date", "Release Date", $days_list, $months_list, $years_list, "");
4- the name "release_date" is then added to the database.
The page shows the three dropdown lists perfectly. But the problem is that the "release_date" in database don't store any value.
I tried the function in step1 and it works perfectly. I know that the problem is in step two, but don't know where.
First your return statement inside show_dropdown_row will not provide you with the date you want. That function will run only once when user request for the page.
So instead of $name1,$name2 and $name3 in your get_dropdown_options function you should put values like. day,month and year as names for your select elements.
When submiting your form at on your php script you should catch those value using post or get.
like.
$dates=$_POST['year']."-".$_POST['month']."-".$_POST['day'];
Related
I'm using
https://pbauerochse.github.io/searchable-option-list/examples.html plugin in my website for searchable dropdown. its working perfectly but i don't know how to get the value of selected items in PHP?
I try to use below code but it return only last selected value in dropdown:
//echo count($_POST['courses']);
// it return only 1 but I select more than 5 items
if (!empty($_POST['courses'])) {
foreach ($_POST['courses'] as $select) {
echo $coursename .= $select. " ";
// only last selected value is displaying
}
}
any one please help...
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 ;)
As I only have one value in the first dropdown, I am trying to create a cascading dropdown in PHP that populates the second dropdown on page load.
My database has a table called 'nights' with fields called: 'city', 'name' and 'day'.
To fill my first box I'm using SELECT DISTINCT cities from nights etc which has worked fine.
To fill the second box I need something along the lines of SELECT name WHERE city = $city - my problem is that I'm not sure how to set $city (being the name of the <select> tag). I can't use $_POST['city'] because the form hasn't been sent at this point.
Any ideas?
If you want this to be dynamic (i.e. after the user changes the dropdown) you will have to use javascript to firstly query a PHP page (probably using jQuery get) then adjust the dropdowns accordingly. There are lots of tutorials for this on the web.
If you just want the initial page data to be populated you can pick the first city from your query and set the option as selected, then use that city in your next query.
Something like:
$first = True;
while($row = mysql_fetch_array($result))
{
echo "<option" . (($first) ? " selected" : "") . ">" . $row['city'] . "</option>";
if($first)
{
$first = !$first;
$city = $row['city'];
}
}
//now do stuff with with $city
<?
$CITIES = query_result("SELECT DISTINCT cities FROM nights;");
if (isset($_POST["city"])) {
$NAMES = query_result("SELECT name FROM nights WHERE city = '{$_POST[city]}'");
if (isset($_POST["day"])
$DAYS = query_result("SELECT day FROM nights WHERE city='{$_POST[city]}'".
" AND name = '{$_POST[name]}'");
else
$DAYS = array();
} else
$NAMES = array();
/* now output the <select> markup for $CITIES, $NAMES and $DAYS */
?>
Note: you have to define the query_result function yourself (I just used it to simplify the code).
You can use AJAX for this.
On change event call javascript-ajax function that call php script which makes you second dropdown caode.
You will need to use ajax to load options from php script.
Here is an example of how you can do it with jquery and ajax:
Autopopulate Select Dropdown Box Using jQuery
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>    ";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>    ";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!
I have a dropdown box that I construct with PHP. Here is the code:
$region_result = mysql_query("SELECT * FROM region ORDER BY region");
$dropdown = "<select name='region'>";
while($row = mysql_fetch_assoc($region_result)) {
$rid = $row["id"];
$region = $row["region"];
$dropdown .= "\r\n<option value='{$row['rid']}'>{$region}</option>";
}
$dropdown .= "\r\n</select>";
I need to set the selected value of the dropdown box AFTER the above code is processed. Is there any easy way to do this?
Does anyone have any suggestions? Thanks!
EDIT:
Thank you all for your answers. Let me explain what I am doing. I was setting up an "Edit Users" page, where you can search for a user by multiple criteria and then the results are listed in an "edit mode" - that is - in text boxes and dropdown boxes. So you can then edit and update a user. For two user fields, I need to list the data in dropdown boxes (to ensure data integrity and constraints). So, I want to show those dropdown boxes with all the possible values you can change to, except I want the selected value of the dropdown to be the one currently associated with the user.
So, I was able to get this working with deceze's suggestion - In my while loop that has that is setting my PHP values with the database results, I have inserted a nested while loop which will construct $dropdown, and within that, a nested if-loop. I'm not crazy about all these nested loops. Here is the code segment for that:
if (#mysql_num_rows($result)) {
while ($r=#mysql_fetch_assoc($result)) {
$fname = $r["fname"];
$lname = $r["lname"];
$region = $r["region"];
$role = $r["role"];
$extension = $r["extension"];
$username = $r["username"];
$building = $r["building"];
$room = $r["room"];?>
<?php
$dropdown = "<select name='region'>";
while($row = mysql_fetch_assoc($region_result)) {
$rid = $row["id"];
$region2 = $row["region"];
if($region == $region2){
$dropdown .= "\r\n<option selected='selected' value='{$row['rid']}'>{$region}</option>";
}else{
$dropdown .= "\r\n<option value='{$row['rid']}'>{$region2}</option>";
}
}
$dropdown .= "\r\n</select>";
?>
However, I am considering changing this to the text replacement (suggested by soulscratch and zombat), as I think it would be better on performance.
...This doesn't seem to work when more than one result set meets the search criteria, though (as the dropdown boxes for the 2nd and 3rd and etc. results are empty).
What do you guys think?
With the way your string is built, it's a fairly simple str_replace(), which is nice as it saves the hassle of needing regular expressions:
$dropdown = str_replace("value='".$rid."'","value='".$rid."' selected=\"selected\"",$dropdown);
If you want to change your assembled HTML after the fact you need to use complicated string replace methods, or Javascript, neither of which is a good choice.
The best option you have would be to restructure your program so you can set the selected attribute when going through the loop the first time around.
You will be able to find it in $_REQUEST['region']
I'll bet you'll run into this problem again, which means it'd be worthwhile to come up with a more flexible solution. Here's an idea toward that end:
First, use an array to hold options for your drop-down list. If you need multiple select elements with the same options, you get to re-use the array for free:
$options = array ();
while ($row = mysql_fetch_assoc($region_result)) {
$options[$row['id']] = $row['region'];
}
Then, you can feed this into a function that generates a select control:
function getSelect ($name, $options, $current)
{
$markup = '<select name="' . htmlspecialchars($name) . '">';
foreach ($options as $value => $label)
{
$selected = ($value == $current) ? ' selected="selected"' : '';
$markup .= sprintf(
"<option value=\"%s\"%s>%s</option>\r\n",
htmlspecialchars($value),
$selected,
htmlspecialchars($label)
);
}
$markup .= '</select>';
return $markup;
}
(You can also add one or more optional parameters to set the id, class, etc.)
Also, you mentioned you were considering switching methods because of speed, but it's very unlikely that this is the time and place to worry about performance. Focus on maintainable code now, and any performance tweaks that become necessary later will be easier and more effective.