After clicking filter button values reseting - php

I've created list of entries from database via HTML table via PHP. There is filters: dropdown (select options) list and text filter.
PHP looks like:
<!DOCTYPE html>
<?php session_start();
ob_start();?>
<html>
<head>
<style>
table, th, td {
border: 1px solid black;
border-collapse: collapse;
}
th, td {
padding: 5px;
}
</style>
</head>
<body>
<form method="post" action="<?php $_PHP_SELF ?>">
<label for="rank">Rank applied</label>
<select id='english' name="RankApplied" class="test">
<option selected disabled value="0">Select value</option>
<option name="RankApplied" value="1">One</option>
<option name="RankApplied" value="2">Two</option>
<option name="RankApplied" value="3">Three</option>
</select>
<label for="VesselsType">Vessel's type</label>
<input id="VesselsType" type="text" name="VesselsType" class="etc" placeholder="Vessel's type"/>
<input type="submit" name="submit" value="Filter" />
</form>
<?php
require("connect.php");
include '../../wp-load.php';
$RankApplied = $_POST["RankApplied"];
$VesselsType = $_POST["VesselsType"];
$UserID = get_current_user_id();
if(isset($UserID)) {
$users = $con->prepare("
SELECT DISTINCT CONCAT(FirstName, ' ', LastName) AS FullName,
RankApplied,
VesselsType
FROM tbl
WHERE FirstName <> ''
AND (RankApplied = '$RankApplied' OR '$RankApplied' = 0)
AND (VesselsType = '$VesselsType' OR '$VesselsType' = '')
");
$users->execute();
$users->bind_result($FName, $RankApplied, $VesselsType);
} else {
echo "There is no User ID detected, try to refresh browser.";
}
?>
<table>
<tr>
<th>Name</th>
<th>Rank</th>
<th>Vessel Type</th>
<th>Preview</th>
</tr>
<?php
while ($users->fetch()) {
?>
<tr>
<td><?php echo $FName; ?></td>
<td><?php echo $RankApplied; ?></td>
<td><?php echo $VesselsType; ?></td>
<td>View</td>
</tr>
<?php
}
?>
</table>
</body>
</html>
If I select for example RankApplied = 'Two' and VesselsType = 'FooBar' after clicking Filter button It filter results correctly, but values for those fielters reseting (RankApplied = 'Select value' and VesselsType = ''), after clicking edit button It should keep/save chosen values.

The code isn't outputting those values. For example:
<input id="VesselsType" type="text" name="VesselsType" class="etc" placeholder="Vessel's type"/>
That just outputs an empty input. Nowhere does it include the value which was posted. You get the value here:
$VesselsType = $_POST["VesselsType"];
Just get it further up the page so you can use it in the output. Perhaps something like this:
<input id="VesselsType" value="<?php=$VesselsType ?>" type="text" name="VesselsType" class="etc" placeholder="Vessel's type"/>
The same concept applies for the select, but is slightly more involved. In that case you'd check if the value equals what was posted and set the selected attribute on an option element. There are a number of ways to do it, and my PHP is very rusty, but something like this might do the trick:
<option <?php echo isset($_POST["RankApplied"]) ? "" : "selected"; ?> disabled value="0">Select value</option>
<option <?php echo $RankApplied == "1" ? "selected" : ""; ?> name="RankApplied" value="1">One</option>
etc...
However you do it, the point remains the same. You need to output those values to the page in order for those values to be on the page.

You can save values with SESSION['rank'] and SESSION['type'] for example and display them when it's filtered.
When user sets the filter and hits the button give those values to session variables and display them.

Related

Dynamic dropdown with auto select one option and it's sub-dropdown options

I have a dropdown in which one is for states and second one is it's sub category, which shows name of cities on basis of first dropdown.
Right now user need to select one category then subcategories load,
What change I want is "To set one value as default and load it's subcategories too" at load of page, and further user select different category so it should load it's subcategories accordingly.
Index.php:
<form name="insert" action="" method="post">
<table width="100%" height="117" border="0">
<tr>
<th width="27%" height="63" scope="row">Sate :</th>
<td width="73%">
<select onChange="getdistrict(this.value);" name="state" id="state" class="form-control">
<option value="">Select</option>
<?php $query =
mysqli_query($con,"SELECT * FROM state");
while($row=mysqli_fetch_array($query))
{ ?>
<option value="<?php echo $row['StCode'];?>">
<?php echo $row['StateName'];?>
</option>
<?php }?>
</select>
</td>
</tr><tr>
<th scope="row">District :</th>
<td>
<select name="district" id="district-list" class="form-control">
<option value="">Select</option>
</select>
</td>
</tr>
</table>
</form>
<script>
function getdistrict(val) {
$.ajax({
type: "POST",
url: "get_district.php",
data: "state_id=" + val,
success: function (data) {
$("#district-list").html(data);
},
});
}
</script>
get_district.php:
<?php
require_once("config.php");
if(!empty($_POST["state_id"])){
$query =mysqli_query($con,"SELECT * FROM district WHERE StCode = '" . $_POST["state_id"] . "'");
?>
<option value="">Select District</option>
<?php
while($row=mysqli_fetch_array($query)){
?>
<option value="<?php echo $row["DistrictName"]; ?>"><?php echo $row["DistrictName"]; ?></option>
<?php
}
}
?>
You would need to do 2 things
1.) insert a selected flag into the input
2.) activate the second dropdown on page load
1.) If the selected entry does never change then hardcode the default selected field in your code like if $var = XXX then echo "selected".
If you have any function which calculates the default value e.g. a geolocation service like e.g. maxmind.com which takes the users remote IP address and outputs his current state, then use this result to set the selected entry.
<?php
while($row=mysqli_fetch_array($query)){
$row["StCode"] == "DESIRED_VALUE" ? $selected ="selected" : $selected ="";
?>
<option value="<?php echo $row['StCode'];?>" <?= $selected ?> ><?php echo $row['StateName'];?>
</option>
[...]
Or add a field in the table SELECTED where you mark the default record with 1.
<?php
while($row=mysqli_fetch_array($query)){
$row["selected"] == 1 ? $selected ="selected" : $selected ="";
?>
<option value="<?php echo $row['StCode'];?>" <?= $selected ?> >
<?php echo $row['StateName'];?>
</option>
[...]
2.) You have to set the second select dropdown on page load. There are several ways to do this - this is explained here in detail:
Jquery execute onchange event on onload

Dropdowns not populating correctly with PHP foreach loop

I am currently populating a table with rows from a database. One of the columns is a dropdown that needs to be populated with multiple values.
Each dropdown is automatically defaulting to Bowling Green even if that row should not be Bowling Green. Most rows are either Southeast or Michigan but regardless of what it should be, it is defaulting to Bowling Green for some reason.
How can I have the dropdowns keep all values as options in the dropdown (bowling green, michigan, southeast), but have the dropdown value default to the value that it is in the database?
<?php
$sql = "SELECT TOP 100 *
FROM Table_OS_List
ORDER BY [CURRENT_SKU] ASC";
$drops = "SELECT [Purchasing_Group]
FROM Table_OS_List
GROUP BY [Purchasing_Group]";
$drop = $dbh->query($drops);
$allDrops = $drop->fetchAll();
?>
<?php
/* Foreach loop that brings in information to populate table */
foreach ($dbh->query($sql) as $rows) {
?>
<tr class="row">
<td class="old_sku" id="old_sku"><?php echo intval ($rows['OLD_SKU'])?></td>
<td class="current_sku" id="current_sku"><?php echo intval ($rows['CURRENT_SKU'])?></td>
<td class="id" id="id" style="display: none;"><?php echo intval ($rows['ID'])?></td>
<td class="dropdown-select" id="purchgroup">
<select id="selected_group" class="selected_group" disabled>
<?php
foreach($allDrops as $dropdown) { ?>
<option class="choice"
value="<?php echo $dropdown['Purchasing_Group'];?>">
<?php echo $dropdown['Purchasing_Group'];?>
</option>
<?php } ?>
</select>
</td>
<td><input type="button" class="edit" name="edit" value="Edit"></td>
<td><input type="button" class="delete" name="delete" id="<?php echo intval ($rows['ID'])?>" value="Delete"></td>
</tr>
<?php } ?>
Example of what it looks like now. You can see that it has multiple options which is what I need, but, regardless of it's value in the database, is defaulting to Bowling Green:
You need to add the selected attribute to the correct option.
Something like this:
<option class="choice"
<?php echo $row['Purchasing_Group'] == $dropdown['Purchasing_Group'] ? "selected" : ""; ?>
value="<?php echo $dropdown['Purchasing_Group'];?>">
<?php echo $dropdown['Purchasing_Group'];?>
</option>
Where $row['Purchasing_Group'] is the column in the Table_OS_List table.
The important code here is <?php echo $row['Purchasing_Group'] == $dropdown['Purchasing_Group'] ? "selected" : ""; ?> - this is known as a Ternary, it could also be written in expanded form like this:
<?php
if($row['Purchasing_Group'] == $dropdown['Purchasing_Group']) {
echo "selected";
}
?>
You can add a selected attribute with a inline ternary operator just like so;
<option class="choice" <?php echo $dropdown['Purchasing_Group'] ? ' selected' : null ?> value="<?php echo $dropdown['Purchasing_Group'];?>">
<?php echo $dropdown['Purchasing_Group'];?>
</option>
and after you fetching all the datas from the DB, always good to check if result or results existing.

Php Jquery Set Multiple selected values from database

I have three multiple select menus. I am trying to select the options returned from a database query. It is not setting any options. I console log the arrays returned by php and they are displayed as:["5233", "7148"]["5233", "5437", "5316"]["7029", "7852", "5525"].
I am not concerned about the form submission at this point. I only want to display the values returned from the db query as selected. I am sure there is something I am missing but can't seem to figure it out. I appreciate all the help I get. Thank you in advance!!
First are my 3 database arrays that are created:
Second is my html:
Third is my javascript/jQuery:
I have three multiple select menus. I am trying to select the options returned from a database query. It is not setting any options. I console log the arrays returned by php and they are displayed as:["5233", "7148"]["5233", "5437", "5316"]["7029", "7852", "5525"].
I am not concerned about the form submission at this point. I only want to display the values returned from the db query as selected. I am sure there is something I am missing but can't seem to figure it out. I appreciate all the help I get. Thank you in advance!!
First are my 3 database arrays that are created:
Second is my html:
Third is my javascript/jQuery:
<?
$huntNum = $hunts[$i][$fm_hunt_fields['__id']];
$cookRole = 'Cook';
$cookVols = get_volunteersByHunt($huntNum, $cookRole);
foreach ($cookVols as $cVols) {
//create new cook array that only contains ID of person
$exCooks[] = $cVols['_id_acct'];
}
$guideRole = 'Hunt Guide';
$hgVols = get_volunteersByHunt($huntNum, $guideRole);
foreach ($hgVols as $hVols) {
$exHg[] = $hVols['_id_acct'];
}
$supportRole = 'General Support';
$gsVols = get_volunteersByHunt($huntNum, $supportRole);
foreach ($gsVols as $gVols) {
$exGs[] = $gVols['_id_acct'];
}
?>
<script>
var existing_cooks = <?= json_encode($exCooks); ?>
var existing_hgs = <?= json_encode($exHg); ?>
var existing_gss = <?= json_encode($exGs); ?>
</script>
<form action="" name="vol-update" id="vol-update" class="vol- update" method="post">
<input type="hidden" id="id_hunt" name="id_hunt" value="<?= $huntNum; ?>" />
<input type="hidden" name="action2" id="action2" value="1" />
<table class="tyhp-account">
<tr>
<td>
<div class="floatL cont_lft_side">
<label for="cooks"><strong>Cooks</strong></label>
<select name="cook[]" class="form-control vCooks" multiple="multiple">
<?php
foreach ($cooksArray as $cook) {
?>
<option
<?
if (in_array($cook['ID'], $exCooks)) {
echo "selected='selected'";
}
?>
value="<?= $cook['ID']; ?>" >
<?= $cook['name_last'] . $cook['name_first']; ?>
</option>
<?
}
?>
</select>
</div>
</td>
<td>
<div class="floatL cont_lft_side">
<label for="hunt_guides"><strong>Hunt Guides</strong></label>
<select name="huntGuide[]" class="form-control vHg" multiple="multiple">
<?php
foreach ($guidesArray as $guide) {
?>
<option
<?
if (in_array($guide['ID'], $exHg)) {
echo "selected='selected'";
}
?>
value="<?= $guide['ID']; ?>" >
<?= $guide['name_last'] . $guide['name_first']; ?>
</option>
<?
}
?>
</select>
</div>
</td>
<?php
$allVols = getAllVolunteers();
?>
<td>
<div class="floatL cont_lft_side">
<label for="supp"><strong>General Support</strong></label>
<select name="gsupport[]" class="form-control vSupp" multiple="multiple">
<?php
foreach ($allVols as $allVol) {
?>
<option
<?
if (in_array($allVol['__id'], $exGs)) {
echo "selected='selected'";
}
?>
value="<?= $allVol['ID']; ?>" >
<?= $allVol['name_last'] . $allVol['name_first']; ?>
</option>
<?
}
?>
</select>
</div>
</td>
</tr>
<tr>
<td> </td>
<td style="text-align:center">
<input type="submit" name="action" id="upVol" class="btn btn-primary" value="Update Volunteers">
</td>
<td> </td>
</tr>
</table>
</form>
//Volunteer information for hunts
<script>
var cooks = existing_cooks;
var hunt_guides = existing_hgs;
var gen_support = existing_gss;
console.log(cooks);
console.log(hunt_guides);
console.log(gen_support);
//Cooks multiSelect
$(".vCooks").val(cooks);
$('.vCooks').multiselect({
columns: 2,
placeholder: 'Select Cooks'
});
//Hunt Guide multi-select
$(".vHg").val(hunt_guides);
$('.vHg').multiselect({
columns: 2,
placeholder: 'Select Hunt Guides'
});
//General Support multi-select
$(".vSupp").val(gen_support);
$('.vSupp').multiselect({
columns: 2,
placeholder: 'Select General Support'
});
return false;
</script>

selected option value in php variable without form tag

I made a cart system in which quantity is getting updated successfully but now i have added two new fields i.e color and size. I want to pass selected values in php variables.I don't want to use <form> tag.Is it possible to do so? I have tried following code. Any suggestions please.
code
<?php
$size = $_REQUEST['size'];//selected size
$color = $_REQUEST['color'];//selected color
if(isset($_GET['action']) && $_GET['action']=="add"){
$id=intval($_GET['id']);
if(isset($_SESSION['cart'][$id])){
$_SESSION['cart'][$id]['quantity']++;
$_SESSION['cart'][$id]['size'];//session for size
$_SESSION['cart'][$id]['color'];//session for color
}else{
$sql_p="SELECT * FROM products WHERE productid={$id}";
$query_p=mysqli_query($con, $sql_p);
if(mysqli_num_rows($query_p)!=0){
$row_p=mysqli_fetch_array($query_p);
$_SESSION['cart'][$row_p['productid']]=array("quantity" => 1, "price" => $row_p['product_price'],"color"=>$color,"size"=>$size);
}else{
$message="Product ID is invalid";
}
}
}
?>
<table border="1">
<tr>
<th>Name</th>
<th>Picture</th>
<th>Description</th>
<th>Price</th>
<th>color</th>
<th>size</th>
</tr>
<?php
$query = mysqli_query($con,"SELECT * FROM products where cat_id=2 ORDER BY product_name ASC");
while($row=mysqli_fetch_assoc($query)){
?>
<tr>
<td><?php echo $row['product_name']; ?></td>
<td><img src="images/<?php echo $row['product_image']; ?>" width="120px" height="120px"></td>
<td><?php echo $row['product_desc']; ?></td>
<td><?php echo "$" . $row['product_price']; ?></td>
<td>Colors:
<select name="color">
<option selected value="choose">choose</option>
<option value="blue" id="blue">Blue</option>
<option value="yellow" id="yellow">Yellow</option>
<option value="green" id="green">Green</option>
</select></td>
<td> <select name="size"><option selected value="Choose size">Choose</option>
<option value="XL" id="XL">XL</option>
<option value="L" id="L">L</option>
<option value="S" id="S">S</option></select>
</td>
<td>Add to Cart</td>
</tr>
<?php
}
?>
</table>
I'd turn it around and make it an actual form. That way, you can select the product, the properties and use the submit button to add it to the cart.
If you want to keep this link, you will need some Javascript to add the properties to the link, but then you're basically recreating a poor man's form using a script and a link.
Using an actual form per product, you can easily let the user select products and add them to the cart, without any need for scripts.
The script I added is just to show the url, since Stack Snippets doesn't make that very obvious.
// Show the post url in the document, since forms are blocked in Stack Snippets.
$('form').on('submit', function() {
document.write(
'about to navigate to: ' +
$(this).attr('action') + '?' +
$(this).serialize());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class="product" method="get" action="add.php">
<input type="hidden" name="product" value="12345">
<select name="color">
<option value="red">red</option>
<option value="green">red</option>
<option value="blue">red</option>
</select>
<button type="submit">Add to cart</button>
</form>
I don't think you can do what you want using PHP alone. I think you are going to have to use a Browser side language like JavaScript.
Do you know you could use tables inside a form?

php edit form, get dropdown to pull value for that record

I have 2 forms, one where I enter records and one where I edit records.
On the form that I add records, I have a drop down which queries another table in my database for the values.
When I click on the "edit" record form to edit this data, I am unable to get the value that has already been entered to be pre-selected in the dropdown.
<select name="aankomstluchthaven">
<option name="aankomstluchthaven" value="">--Select--</option>
<?php
$list=mysql_query("select luchthavenID, luchthavencode from tbl_luchthaven
order by luchthavencode ASC");
while($row_list=mysql_fetch_assoc($list)){
?>
<option value="<?echo $row_list['luchthavenID']; ?>"> <?echo
$row_list['luchthavencode']; ?> </option>
<?
}
?>
</select>
the field that is being updated is 'aankomstluchthaven'. So the value from my table where the form data is stored (tbl_vluchtgegevens) should be populated.
Where tbl_luchthaven.luchthavenID = tbl_vluchtgegevens.aankomstluchthaven
I tried putting in the option value, but that is not what I"m looking for.
Edit to include example php page with dropdown (note, I have changed from aankomstluchthaven in the example above to vertrekluchthaven in the example below. same thing applies.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>bijwerk vluchtgegevens Form</title>
</head>
<body>
<? include "datalogin.php";//database connection
$order = "SELECT *
FROM tbl_vluchtgegevens
WHERE gegevenID='$id'";
$result = mysql_query($order);
$row = mysql_fetch_array($result);
?>
<table border=1>
<tr>
<td width="547" align=center>bijwerk vluchtgegevens: <br>
gegevenID = <? echo "$row[gegevenID]"?></td>
<td width="547" align=center> </td>
</tr>
<tr>
<td>
<table>
<form method="post" action="bijwerkvlucht_post.php">
<input type="hidden" name="id" value="<? echo "$row[gegevenID]"?>">
<tr>
<td width="208">Vertrekluchthaven </td>
<td width="325">
<select name="vertrekluchthaven">
<option name="vertrekluchthaven" value="">--Select--</option>
<?php
$list=mysql_query("select luchthavenID, luchthavencode from tbl_luchthaven order by luchthavencode ASC");
while($row_list=mysql_fetch_assoc($list)){
?>
<option value="<?echo $row_list['luchthavenID']; ?>"> <?echo
$row_list['luchthavencode']; ?> </option>
<?
}
?>
</select>
</td>
</tr><tr>
<td align="right">
<input type="submit"
name="submit" id="submit" value="Submit"> </td>
</tr>
</form>
</table> </td>
<td> </td>
</tr>
</table>
<?php
// close connection
mysql_close();
?>
</body>
</html>
Assuming you are getting the values by id or whatever when you edit the form, you would do something like this:
<option value="<?echo $row_list['luchthavenID']; ?>" <? echo ($row['luchthavenID'] == $row_list['luchthavenID'] ? ' selected="selected"' : ''); ?>> <?echo $row_list['luchthavencode']; ?> </option>
Each time through the loop you check the value against the values pulled in the query. If they match, you make this option selected.
UPDATED
I still don't know what your field is called, but assuming it is $row['luchthavenID'] I would write it like this:
echo '<option value="'.$row_list['luchthavenID'].'"'.($row['luchthavenID'] == $row_list['luchthavenID'] ? ' selected="selected"' : '').'>'.$row_list['luchthavencode'].'</option>';

Categories