I'm working on an old, out of date webpage which displays data from a database. My task is to enable the selection of some values in order to narrow down what the user is looking at.
I have created a dynamic dropdown list based upon what a certain field within the database is set to. The problem I am having is that once the dropdown selection is made the dropdown resets to default.
I've looked through methods to allow to option to be retained once selected and the page refreshes. However these all require php statements which doesn't work with the method I have used.
Please see the code below. Please ignore $past as this is a variable set for a certain amount of time in the past.
<?php
//Section to fill the Department dropdown
$dropdown = "SELECT `ResponsibleGroup` FROM 'table` WHERE `Change_Start_Time` > '$past' AND `Change_Start_Time` < '$future' AND `Status` NOT LIKE 'Cancelled' AND `Status` NOT LIKE 'New' AND `Status` NOT LIKE 'Re-Scheduling' GROUP BY `ResponsibleGroup` ORDER BY `ResponsibleGroup` ASC";
$dropres = mysqli_query($con,$dropdown);
while($row = mysqli_fetch_array($dropres))
{
echo"<option value='" .$row['ResponsibleGroup'] ."'>" . $row['ResponsibleGroup'] . "</option>";
}
?>
</select>
</form>
The suggestions I've seen suggest putting an if isset PHP statement in the field however, i've not been able to get this to work. I've tried doing exactly as they suggested and just using <?php .... within the echo, which doesn't work. Like the below:
<select name="operator">
<option value="add" <?php echo (isset($_POST['operator']) && $_POST['operator'] == 'add') ? 'selected' : ''; ?>>+</option>
I've also tried similar to the above while breaking out of the echo but i can't get that to work either.
Any help or advice on this topic would be greatly appreciated.
Thanks in advance.
I have found the solution for this.
<script type="text/javascript"> document.getElementById('department').value="<?php echo $_POST['department'];?>"; </script>
Related
Having solved the populating the dropdown from the array, the next phase of my project is pulling data from a database to allow users to put limits on the data they want to see.
Again, I'm having trouble populating the dropdown. This time however, the problem seems to be that when I put the HTML interspersed with the PHP, the whole thing stops- the form loads, but nothing goes into the drop down.
Here's the code.
//Step One: Query the DB, and get a list of monthly reports
$sql = "SELECT Report_Text, Report_Date FROM ADM_8_Reports_List";
$result = $conn->query($sql);
//print_r ($result);
$reports_in_db = mysqli_fetch_all($result,MYSQLI_ASSOC);
if (sizeof($reports_in_db) > 0)
{
print_r ($reports_in_db);
echo "\n";
//Now, like the front page, create a form and populate it.
?>
Choose a Monthly Report <select name = "monthly_report">
<?php
foreach($reports_in_db as $row)
{
echo 'option value"' . $row ["Report_Date"] . '">' . $$row ["Report_Date"] . " " . $row ["Report_Text"] . '</option>';
}
}
else
{
echo "I'm sorry, there's no data here. Please start again\n";
} ?>
</select>
<input type="submit" name="monthly report" value="Retrieve Report"">
the output
what it looks like is happening is that the code is freezing where I'm interpolating the HTML and PHP, and actually creating the dropdown.
basically on the previous page, the user can choose one of 4 things to do. On this page, there's an if statement based on $_POST from the previous page. Depending on the choice, the databased will be polled to get, in this case, a list of all the monthly reports. I've copied exactly the structure of what I did on the first page (where I was going from an associative array I hard-defined). I can't figure out what's wrong with the declaration of the dropdown, but that's where the thing's .. well stopping.
I am really annoyed by this.
I forgot '<'when declaring the option. And didn't see it until I posted the question here.
Sorry.
I've hit a crossroad while coding up a search filter, and I don't even know the verbiage for a practical search.
I have a form that generates values based on SQL, then I'm using php on the display page to format these values for an SQL search. My desired behavior is to include an option in the html form that bypasses this specific filter to show all products. My previous solution has been to include IS NOT NULL as the value of one of the options, however that was before I generated form data based on the SQL values.
Here's my desired behavior as best I can explain (this is not my code, just a coded-explanation).
if $productnamesort == " IS NOT NULL" -> do nothing (leave value as " IS NOT NULL")
if $productnamesort != " IS NOT NULL" -> append characters before and after the value (=' before and ' after)
So I need to format the output of $productnamesort to essentially be one of two things
1) " IS NOT NULL"
2) ='$productnamesort'
Just for a little more detail, here are the relevant pieces of code.
Form Input
<select class="selectinput" name="filter_product_name">
<option value=" IS NOT NULL" selected>All Products</option>
<?
$r = mysql_query("select product_name from products");
while($row = mysql_fetch_assoc($r)){
echo "<option value='{$row['product_name']}'>{$row['product_name']}</option>";}
?>
</select>
Current PHP Formatting (where I need some help)
$productnamesort = $_POST[ 'filter_product_name' ];
I know there are a variety of ways to address this issue, if anyone has something more efficient I'm eager to learn.
Thanks!
I would not recommend doing it like this.
You could make your form like this:
<select class="selectinput" name="filter_product_name">
<option value="all_products" selected>All Products</option>
<?
$r = mysql_query("select product_name from products");
while($row = mysql_fetch_assoc($r)){
echo "<option value='{$row['product_name']}'>{$row['product_name']}</option>";}
?>
</select>
Then you could do something like this for the query:
<?php
if($_POST['filter_product_name'] == 'all_products') {
// Query like Select * from products
} else {
// Query like SELECT * FROM products WHERE name = '".$_POST['filter_product_name']."'
}
I know that my last part is pseudo-code, but you should be able to figure it out.
This is not a good thing to use mysql_* functions, but you can do the following :
$productnamesort = $_POST[ 'filter_product_name' ];
if ($productnamesort != " IS NOT NULL")
$productnamesort = "'".mysql_real_escape_string($productnamesort)."'";
A better solution is to use mysqli_* or PDO functions (mysql_* is deprecated and will be removed in future releases).
You can easily follow the examples given in the official documentation for mysqli_prepare or PDO::prepare.
I have a select box being filled in with a mysql query, it functions fine and is selectable. Data changes and works fine.
It currently sorts based on the branch_id column and what I want is the session variable of $branch_id to be the first option of the select box. This is based on the branch selected from a previous page.
This is where I am stuck.
Here is some sample code of the branch dropdown.
This selection then changes a list of users that appears in an options box below this code. It all functions fine, I just need to refine it so the currently selected branch(from a prev page) is the first in the branch dropdown.
If anyone can help I'd really appreciate it.
//get list of allowed Branchs
$AllowBranch = "SELECT branch_id FROM access WHERE userid IN (SELECT id FROM user WHERE username = '{$_SESSION['user']}') ORDER BY branch_id ASC";
$getAllowBranch = mysql_query($AllowBranch);
while($getAllowBranchRow = mysql_fetch_assoc($getAllowBranch))
{
$NameSQL = "SELECT name FROM branchlist WHERE id = '{$getAllowBranchRow['branch_id']}'";
$Nameresult = mysql_query($NameSQL);
$Namerow = mysql_fetch_assoc($Nameresult);
echo "<OPTION VALUE = '{$getAllowBranchRow['branch_id']}' "; if($NeedBranch == $getAllowBranchRow['branch_id']) { echo "selected"; } echo "> ".ucwords(strtolower($Namerow['name']));
}
echo "</SELECT>";
Check the source code to see if the selected attribute is put in the right option tag. Also, you forgot to close every <option> tag with a </option>, not sure, but this could also be the problem.
First of all, you have missing tag <select name="<your field name>"> before while loop.
Then you have missing closing tag </option> too. You cannot solve your problem, if you have HTML broken.
So, it should looks like this:
echo '<select name="<your field name>">';
while($getAllowBranchRow = mysql_fetch_assoc($getAllowBranch))
{
$NameSQL = "SELECT name FROM branchlist WHERE id = '{$getAllowBranchRow['branch_id']}'";
$Nameresult = mysql_query($NameSQL);
$Namerow = mysql_fetch_assoc($Nameresult);
echo "<option value='" . $getAllowBranchRow['branch_id'] . "'" . $NeedBranch == $getAllowBranchRow['branch_id'] ? " selected" : "" . ">" . ucwords(strtolower($Namerow['name'])) . "</option>";
}
echo "</select>";
What I have done?
Firstly, I fixed your missing HTML tags. Then I just simply used ternary operator to check if branch_id equals to $NeedBrach and if yes, add following string selected and if not, add nothing.
Don't forget to replace <your field name> with your expect select name.
Important final thoughts!
I have to remind using mysql_* is deprecated, you should use mysqli_* or PDO instead with prepared statements.
i'm trying to make a simple webpage for making invoices. to select/load customer info i'm using a select dropdown filled with all the customers in the database.
after selecting a customer i want php to get all the values of that customer from the database and echo somewhere else on the page.
thought it would be something simple but tried everything and cant seem to get it to work.
any help?
after deleting all the code that didn't work anyway this is what i'm left with:
<select name="selectCustomer">
<option selected>Klantnaam</option>
<?
$result = mysql_query('SELECT * FROM '.$c_tbl_name);
while($row = mysql_fetch_array($result)) {
echo '<option value="'.$row['c_id'].'">';
echo $row['c_name'];
echo '</option>';
}
?>
</select>
You need some small AJAX function to do that:
jQuery(document).ready(function($){
$('[name="selectCustomer"]').change(function(){
$('#result').load('load_data_from_db.php', {
customer : $(this).val();
});
});
});
You than need a script load_data_from_db.php which takes the selected customer, generates the content and returns it to the client where it would be placed into an element with the ID result.
Try
$result = mysql_query('SELECT * FROM '.$c_tbl_name) or die(mysql_error());
and this will give info if the query failed.
Furthermore, you should really consider upgrading from mysql() as it is now deprecated. Try google search for 'php PDO'.
Can any one please help me? I am new to php, currently I am trying to use $_POST['item'] to obtain a string (consists of many words) from a dropdown box and then process it. However, when I use $_POST['item'], only first word is returned, the rest of words are missing.
I have a dropdown box, something like:
echo "<form action='process_form.php' method='post'>";
echo "Select an item<br />";
echo "<select name='item' id='item'>";
...
...
...
each item in the dropdown box is a string that has product names like:
dressmaker mannequin size 12
torso mannequin in white color
...
User will then select an item from the dropdown box. When I used $_POST['item'] to obtain this string, I get the first word "dressmaker", all the rests were missing.
How do I get the whole string?
Many thanks in advance.
I am not sure exactly what you are doing but I would do something like this. For this example I assume that the values "dressmaker mannequin size 12" will correspond to the values of the columns in the database to which I will refer to as "colA, colB, colC, and colD", and in addition I assume you have an "ID" column in your database.
Here is the code I would use to generate the select drop-down list:
//$query is the variable storing the result of the mysql_query();
//assumption is that the result-set is non-empty
echo '<select name="item" id="item">\n'; //\n - new line character
//run through the loop to generate the items inside the list
while ($result = mysql_fetch_assoc($query)) {
//note the id - it will be used to find data in the
//database after the POST is complete
//couple of temp variables (not necessary but makes code cleaner)
$database_id = $result["ID"];
$colA = $result["colA"]; //ex:dressmaker
$colB = $result["colB"]; //ex:mannequin
$colC = $result["colC"]; //ex:size
$colD = $result["colD"]; //ex:12
//add option to the select drop-down
echo "<option value=\"$database_id\">$colA $colB $colC $colD</option>\n";
}
echo "</select>";
Now to retrieve the data from the POST. I am including the code Drewdin suggested.
//form was submitted already
//assumption is that the database connection is established
$item_id = mysql_real_escape_string(trim($_POST["item"]));
//Now get the info from the database for this id
//table is "table"
$string = "SELECT * FROM table WHERE ID = $item_id";
$query = mysql_query($string) or die("Could not complete the query: $string");
//assumption here is that the result set is non-empty
$result = mysql_fetch_assoc($query);
$colA = $result["colA"]; //ex:dressmaker
$colB = $result["colB"]; //ex:mannequin
$colC = $result["colC"]; //ex:size
$colD = $result["colD"]; //ex:12
//now you can use the values of colA-D to compute whatever you want
Hope this helps. Using database ids is nice for security plus it makes things more manageable.
Regarding using this blog. You can post comments to the answers people post. If you want however to add something to your question, you can edit your original question and just make sure its obvious what was added.
When the issue is resolved and if any answer helped and you liked it, you can pick it as the final answer by clicking the check mark next to it.
Best of luck
without seeing your select options i think this might help you
if (isset($_POST['submit'])) {
// Grab the output of the select list
$Select_Output = mysqli_real_escape_string( $dbc, trim($_POST['item']));
//What ever else you want to do here...
}
I also would use Miki725's post to make sure your select list is setup correctly
This is how the php gets the values from the HTML select item:
<select name="item" id="item">
<option value="this is option 1">option 1</option>
<option value="this is option 2">option 2</option>
<option value="this is option 4">option 3</option>
...
</select>
Basically you would do something like:
$var = $_POST['item'];
The $var will be the whatever was entered into the "value" of the option tag. So just make sure you have the proper values entered into the value fields.
Hope that helps.