avoid reloading page or resetting select dropdowns with php - php

I'm new to PHP programming and working with backend. I know what I am doing, but having trouble finding a proper solution online which matches my case.
Basically, I have a form (2 text fields, 3 dropdowns) that filters the data that I am getting from SQL Server (that works). However, when I press the "filter" button and I get the desired results, the page reloads and resets the form. Now I have the filtered records but I don't know what filters I used to get that. I could insert a <?php ... ?> if else, but the thing is I already am using php to get the dropdown values. Don't think I can put php inside php.
By including if-else I mean this:
echo '<option value="' . $row['status'] . '"' . if($prod_status == $row['status']): echo ' selected="selected"' . '>' . $row['status'] . '</option>';
Here's the code:
<label for="prod_status_filter">Prod Status</label>
<select class="form-control" id="prod_status_filter" name="prod_status_filter">
<?php
$query_status = 'select DISTINCT status FROM analytics.laborrecords ORDER BY status ASC';
$result = sqlsrv_query($conn, $query_status);
while ($row = sqlsrv_fetch_array($result, SQLSRV_FETCH_ASSOC))
{
echo '<option value="' . $row['status'] . '">' . $row['status'] . '</option>';
}
?>
</select>
This is one of the dropdowns.
I want:
1. Either stop the page from reloading so the filter dropdowns remain the same. (AJAX won't work, I have 3 dropdowns with a lot of options and it's doesn't seem like a good practice to make so many getElementById lines)
2. Let the page reload but keep the values as I set until I want to reset them, with a "reset" button.

You have to populate the form using the submitted form data. It should be either in $_POST or $_GET.
Check if the value of $_POST['prod_status_filter'] matches the value in $row['status'] and if it does, echo selected.
Be sure to sanitize the form data. Never trust user input.

Related

PHP ECHO table with dynamic dropdown as one column using FOR EACH

I am a bit stuck I am attempting to build out a table with HTML and PHP. Ok got that done. Now I want to add a dynamic dropdown as one of the column options but cant seem to figure out how to mix the PHP, the HTML and the needed FOR EACH loop.
I know its currently wrong but am posting a variable of what I have been trying below.
echo '<td>' . "<select>". "<option value =" . $sf_name . ' '. $sl_name . ">" . $sf_name . ' '. $sl_name . "</option>" .
foreach($Staff_On_Duty as $person){
"<option value =" . $sf_name_option=$person->Staff_First_Name . ' '. $sl_name_option=$person->Staff_Last_Name . ">" . $sf_name_option . ' '. $sl_name_option . "</option>"
}
. "</select>" .'</td>';
I need to have the currently selected individual at the top of the dropdown with the option to change that person out. the first .sf_name comes from higher in the code and gives me the name of the individual currently selected. The foreach runs from the $Staff_On_Duty query to give me everyone working right now. What is the right way to do this?
This is how I would do it, essentially only fill the dropdown and mark the option that should have been selected (other stuff is a matter of preference):
echo("<td><select>");
foreach($Staff_On_Duty as $person){
$sf_name_option=$person->Staff_First_Name; // separated for clarity, you could also use $person->Staff_First_Name everywhere
$sl_name_option=$person->Staff_Last_Name;
echo("<option value = $sf_name_option $sl_name_option");
if (($sf_name_option == $sf_name) && ($sl_name_option == $sl_name)) echo (" selected"); // this is the relevant part, but make sure variable values match!
echo(">$sf_name_option $sl_name_option</option>");
}
echo("</select></td>");
Note that I did not put any quotation marks cause I have no idea what your variables entail, but it would need them if you don't have them in yet, i.e.:
... value=\"$sf_name_option $sl_name_option\" ...

Update mysqli query from html select

I have a tests.php web page that successfully creates and populates a html table using data from a mysql database on an online server. Next I want to make the web page interactive by adding html select to limit the number of rows the sql query returns. I've added the html select code and amened my sql query to use a variable for LIMIT. The issue I have is how to make the query run when the select dropdown is changed. I'm assuming some kind of page refresh needs to be called but unsure how to go about this. For example would I need to enclose the html as a from and have a submit button to make this work? This IS NOT what I want, ideally the user presses html select and then the page refreshes or re runs the sql database query.
Please be kind this is the first php code I've written.
My select code
<select name="limit" id="limit">
<option value="10">10</option>
<option value="25">25</option>
<option value="50">50</option>
<option value="100">100</option>
</select>
The php code
</body>
</html>
<?php
$limit = 10;
if(isset($_POST["limit"])) $limit = $_POST["limit"];
$con=mysqli_connect("localhost","user","password","database");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM TableName WHERE Region='Home' ORDER BY TeamName ASC LIMIT $limit");
echo "<table class='sample' style='width:50%'>
<tr>
<th>Team Name</th>
<th># Players</th>
<th>Venue</th>
<th>Date</th>
<th>Score</th>
</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['TeamName'] . "</td>";
echo "<td>" . $row['NumPlayers'] . "</td>";
echo "<td>" . $row['Venue'] . "</td>";
echo "<td>" . $row['Date'] . "</td>";
echo "<td>" . $row['Score'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
UPDATE
I think I may have a simpler solution using javascipt although it's not working correctly.
Using javascript function:
window.location.reload(true);
and change my html select
<select onchange="refresh.call()">
However when the page re loads it's using the typed $limit value
$limit =10;
instead of the select value.
The page refresh is working but is there a way to inject the html select value somehow?
Sanitizing Input
First off, you need to sanitize your limit variable as it's insecure to allow input directly into the SQL.
see:
What's the best method for sanitizing user input with PHP? AND
https://www.shift8web.ca/2015/06/securing-your-mysql-queries-from-sql-injection-in-php/
Single Page App Approach
Secondly, you need to decide if you will re-write the html notes using javascript ( in which case you will make an ajax/jquery request). Then you will rewrite the html using some framework or javascript ( innerHTML = '') or editing the DOM tree.
See:
Ajax tutorial for post and get
AND
https://stackoverflow.com/a/19527642/1688441
Reloading the page
If you decide you don't want to use javascript to rewrite the Dom tree, then the only solution is to refresh the entire page using either a GET or POST with the limit parameter.
So you will use an onChange listener, and call the page again with a limit parameter.
See: Reload page after user clicks on combobox (with some rules)

Modx: FormIT Select fields not persistent when values are loaded from MySQL table

I know that the formItIsSelected utility works perfectly well to keep the value of a Select field in a form when (for example) the form fails to validate for some reason. But has anybody tried to use this when a Select field populates from a table in MySQL? This is surely more useful than a Select field populated with static values..
I have a form in a modx site, hooked with formit and a select field in it retrieves dynamically values from a table in MySQL. When the form fails to validate this specific field loses the value the user has selected. My field (in the form) has the following setting:
<select id="Field245" name="typeOfRelationship" class="field select medium" tabindex="4">[[!getRelationshipOptions? &selected=`[[!+fi.typeOfRelationship]]`]]</select>
and the snippet and which works correctly simply does:
<?php if (!$modx->addPackage('contacts', MODX_CORE_PATH . 'components/contacts/model/')) {return 'Could not load xPDO model';}$current = $modx->getOption('selected', $scriptProperties, '');$output = [];$relationships= $modx->getCollection('RelationshipCodes');foreach ($relationships as $relationship) {$selected = $current == $relationship->get('codes') ? 'selected="selected' : '';$value=$relationship->get('descriptions');$output[] = '<option value="' . $relationship->get('descriptions') . '" ' . $selected . '>' . $relationship->get('descriptions') . '</option>';}return implode('', $output);
So far so good. But when I replace the $output[] line with:
$output[] = '<option value="' .$value . '" '. '[[!+fi.typeOfRelationship:FormItIsSelected=' ."'".$value. "'". $selected. ']]>' . $value . '</option>';
this fails! It doesn't error but it still allows the Select field to lose its setting when the form fails validation. Do you see a problem? Or maybe FormItIsSelected does not work in that context?
Many many thanks

Varying a group of drop down boxes

I want a search page with five fields from the MYSQL database shown in individual drop down boxes. I have a basic drop down, adapted from one of the other answers here which I have reproduced five times for each of the fields.
$sql = "SELECT Country FROM engravers";
$result = mysql_query($sql);
echo "<select name\\='Country'>";
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row['Country'] . "'>" . $row['Country'] . "</option>";
}
echo "</select>";
Repeating with obvious changes gives me five neat little drop down boxes that all work.
I want all of the boxes to be interactive so each box will have a default of "all" unless clicked. That means a user could click on a country and a year and get only the records that fit both criteria.
I want a single submit button to handle them all.
It is simple.
echo "<select name='Country'>";
echo "<option value=''>All</option>";
To get the submit button to submit all of them, just put them all in the same form.
(How you handle the '' option in the search depends on the code that processes the form data)

How to generate a state/province dropdown that selects the value in the database

So I have several places for country and state/province dropdowns. What I'd like to do is have a function for each of these and when I run my while loop on customer data from mysql I want to select the right by default from the data in the database.
Reason is right now the dropdowns default to the HTML selected one so if users don't change it to theirs again when they edit their account they re-save their info with the wrong state/country.
I'd also like to use this in several places so I want a big array of countries and states/provinces that loop.
Just looking for a hand or be pointed to where this has been done in a function already.
Thank you kindly.
$states - query with all states, $user_state - current user's state. So your user's choice will be selected by default.
<?php
echo '<select name="state">';
while ($state = mysql_fetch_assoc($states))
{
echo '<option value="' . $state['state'] . '"';
if ($user_state == $state['state'])
{
echo ' selected';
}
echo '>' . $state . '</option>';
}
echo '</select>';

Categories