Displaying form selected option results from database - php

Okay, I'm reframing this whole question because the earlier version was a bit convoluted.
Here's the scenario:
I have a MySQL table called "churches."
I have a form with four selects. The options are drawn dynamically from the table, so that users can search on four table columns to find churches that fit the criteria (country, state/province, city, presbytery)
I also have working code to get all the table data to display.
What I haven't figured out is how to use the selected option from the form to filter the results.
My current code is below:
<form action="display0506b.php" method="post">
<select name="country">
<option value=""></option>
<?php
$query = mysqli_query($link, "SELECT DISTINCT country FROM churches");
$query_display = mysqli_query($link,"SELECT * FROM churches");
while ($row = mysqli_fetch_array($query)){
echo "<option value='" . $row['id']."'>". $row['country'] . "</option>";
}
?>
</select>
<select name="state">
<option value=""></option>
<?php
$query = mysqli_query($link, "SELECT DISTINCT state FROM churches WHERE state != ''");
$query_display = mysqli_query($link,"SELECT * FROM churches WHERE state != ''");
while ($row = mysqli_fetch_array($query)){
echo "<option value='" . $row['id']."'>". $row['state'] . "</option>";
}
?>
</select>
<input type="submit" value="Go!">
</form>
<?php
if(isset($_POST['country']))
{
$name = $_POST['country'];
$fetch = "SELECT * FROM churches WHERE id = '".$name."'";
$result = mysqli_query($link,$fetch);
echo '<div class="churchdisplay">
<h4>' .$row['churchname'].'</h4>
<p class="detail">' .$row['detail'].'</p>
<p><b>' .$row['city'].'</b>, ' .$row['state'].' ' .$row['country'].'</p>
<p>' .$row['phone'].'</p>
// etc etc
</div>';
}
else{
echo "<p>Please enter a search query</p>";
}
?>
Note that in the form above, I only have two selects for illustration, but ultimately I will have four, as mentioned; and I am only attempting the country selection at this point to keep things simple. Ultimately, I will need the ability to select any (and preferably all) of the four categories.
As you can see, this code does attempt to "grab" the selected value from the form, but it's not working. I've pondered numerous tutorials and examples, but none of them do exactly what I'm after, and as an extreme PHP novice, I'm stumped.
So the question: how do I tweak this so that I can "grab" the form selection and display the relevant results from my table?
Edit: I am using mysqli syntax, and want to just use PHP and MYSQL (no Ajax etc) if possible.

Well, it looks like I've finally found what I needed here:
display result from dropdown menu only when value from it is selected
Or, I should say, I've got it to work with one select option. Still need to see if I can figure out how to get four working together.

Related

PHP - populate a select drop down from MySQL DB and have that field auto-populated in a form

I am trying to accomplish two things with the code below. Firstly I want my select options to be populated form my database. Secondly I want the field in the form to have the stored value selected on page load (like in a profile for a member). The way I have implemented below works, kind of, but I have two problems. Firstly if you open the dropdown then the selected option appears twice (once at the top and once in its normal position). Secondly if it is a required field then the user has to open the dropdown and select it again, even though it is appearing in the field (horrible ux). If it is not a required field the form acts as if nothing is selected and I get a Undefined index error further down the line. I am very sure there is a better way to implement what I am trying to achieve that wont give me these problems... all help greatly appriciated.
<?php
$query6 = "SELECT catname FROM travisor_catagory";
$result6 = mysqli_query($conn, $query6) or die(mysqli_error($conn));
$queryread3 = "SELECT * FROM travisor_catagory WHERE id = $catagory";
$result3 = mysqli_query($conn, $queryread3) or die(mysqli_error($conn));
if (mysqli_num_rows($result3) > 0) {
while ($row = mysqli_fetch_assoc($result3)) {
$cat = $row["catname"];
}
}
echo "<div class='form-group'>
<label>Catagory *</label>
<select class='form-control' name='catagory' required>
<option disabled selected value> $cat </option>";
if (mysqli_num_rows($result6) > 0) {
while ($row2 = mysqli_fetch_assoc($result6)) {
$catagory2 = $row2["catname"];
echo "<option>$catagory2</option>";
}
}
echo "</select>"
?>
Don't mix things up so much.....
When you get into larger programs, you will get lost really quickly, so K.I.S.S.!!!
You can 'jump' in/out of HTML and back to PHP to echo the $options variable, then back to HTML to complete the select. (this is my description of it when I teach newbies - this concept of 'jump in/out' works for PHP, HTML, JS - well any languages that you can combine in one page... - it is worth grasping the concept!)
First, get the options you will need with ONE query (watch how we take care of the selected one as well) - this will make a 'packet' of data in the $options variable.
<?php
// declare some values that we'll use later
$options = '';
// gather the data for the options
$sql = "SELECT id, catname FROM travisor_catagory";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
$selected = '';
if($category == $row['id']){
$selected = "selected";
}
$options .= '<option ' . $selected . ' value="' . $row["id"] . '">" . $row["catname"] . "</option>";
}
}
// now we will 'jump' out of PHP and back to HTML
?>
<!-- we are in HTML, so comments and language changed... -->
<div class='form-group'>
<label>Catagory *</label>
<select class='form-control' name='catagory' required>
<!-- here we 'jump' out of HTML and into PHP to use the $options variable -->
<?php echo $options; // and back out of PHP to HTML... ?>
<!-- where we finish up our select and whatever other HTML things -->
</select>
</div>
That should take care of both your issues with what you had.....
BTW, it looks like you are using Bootstrap - if so, I HIGHLY recommend you check this out (changed my life about fighting with select boxes! :) Bootstrap Select

Selecting the value of a mysql populated drop down list

I am trying to use the value of a mysql populated dropdown list in with php and keep getting a blank return. I have scoured the internet and found very similar questions on here to my problem but everyone i try seems to fail. The select list populates without a problem using the code below.
<form action="includes/insertEquine.php" method="POST">
<label for="select-gender" class="select">Choose Gender</label>
<select name="select-gender id="select-gender">
<?php
$sql = ("SELECT genderType FROM gender");
$result = mysqli_query($con, $sql);
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
echo "<option value ='".$row['genderType']."'>" . $row['genderType'] . "</option>";
} ?>
</select></form>
when i try to select it using the below I get an empty space returned.
<?php $genderType = $_POST['select-gender']; ?>
Any further suggestions would greatfully recived.
I have already looked at the below with no success
Getting value from populated drop down list
and
How to dynamically get the value of a select tag from MySQL table .
You are missing a " in
<select name="select-gender id="select-gender">
So replace it as
<select name="select-gender" id="select-gender">
That is why you arent getting a value with key select-gender in $_POST

Implement data using query

I want to create a php page that contains a html drop down list of people's names (as the option
text) and then their age (as the value). Below is my form for you to see (almost what I mean) which I hard coded:
<form>
<select name="nameOption">
<option value="">Select your name:</option>
<option value="45">Mary Smith</option>
<option value="16">Lily Roe</option>
<option value="32">Elliot Perkins</option>
</select>
<p><input type="submit" name="submit" value="Submit"/>
<input type="reset" value="Reset" />
</form>
What I want to do (or been trying to do) is to create the drop down list by running a SQL query to obtain the data (the people's name and age) from my database (unlike what I written above) and then when I click on one of the options, only their value or age should appear. So basically, I need to implement the data from the database into a drop down list
Now it's here where I am stuck. I am familiar with writing SQL statements for tables but I seem to get puzzled when I try to create a SQL statement for a drop down list in a php tag.
How would I write it? Like:
$sql = "SELECT name, age FROM person WHERE name = ". $person. ";
or
$nameOption = $_POST['nameOption'];
print_r ($nameOption);
with selecting a database:
$conn = mysql_connect("localhost", " ", " ");
mysql_select_db(" ", $conn)
I know it may seem like a dull answer but I need help. How would I implement SQL query to a drop down list? I would love your help.
As you have to enclose string in quotes, change your query to
$sql = "SELECT name, age FROM person WHERE name = '$person'";
and for showing dropdown dynamically you can do like
$query=mysql_query($sql);
echo '<select name="nameOption">
<option value="">Select your name:</option>';
while($result=mysql_fetch_array($query))
{
echo '<option value="'.$result['age'].'">'.$result['name'].'</option>';
}
echo '</select>';
You should do like that
<select name="nameOption">
<?php
$query = mysql_query($sql);
while( $row = mysql_fetch_array($query) ) {
echo '<option value="'.$row['age'].'">"'.$row['name'].'"</option>';
}
?>
</select>
You need to get the full list of people from the database first, then iterate through that outputting each option tag for each row:
$cnx = new Mysqli('localhost', 'username', 'password', 'database_name');
$people = $cnx->query("SELECT name, age FROM person");
echo '<select name="nameOption">';
while($person = $people->fetch_assoc())
{
echo '<option value="' . $person['age'] . '">' . $person['name'] . '</option>';
}
echo '</select>';

How to populate dependant select menus dynamically using jQuery, PHP and MySQL?

I have searched quite a bit on here about this topic. But I could not find a solution for my problem. I'd appreciate it a lot if you could help me, this is for a school project I am working on.
I have a database with a table ("Main_table") and columns including "sector" and "sub_sector". I want to have two select boxes, first one will load all the records from database in "sector" column and the second one will load all the records from database in "sub_sector" column depending on the selection value of the first select box. (For example: If I select "plastics" on the first select box, then second select box should be updated with sub_sector values where sector value is equal to "plastics").
I have managed to load the options values from database for the first select box but when I click on any selection, it does not load any option to the second select box. You can find the codes below. I did not put "sector_options.php" below, as it seems to work just fine.
index.html shown below:
<script>
$(document).ready(function() {
$('#filter_sector')
.load('/php/sector_options.php'); //This part works fine - uploads options to the first select box
$('#filter_sector').change(function() {
$('#filter_subsector').load('/php/subsector_options.php?filter_sector=' + $("#filter_sector").val()
} //This part does not work - no options on the second select box
);
});
</script>
<body>
<div id="sectors"><p>Sector:</p>
<select id="filter_sector" name="select_sector" multiple="multiple" size="5"> </select>
</div>
<div id="subsectors"><p>Sub Sector:</p>
<select id="filter_subsector" name="select_subsector" multiple="multiple" size="5"> <option value="" data-filter-type="" selected="selected">
-- Make a choice --</option>
</select>
</div>
</body>
</html>
sector_options.php shown below:
<?php
$link = mysqli_connect("*******", "*******","******","********") or die (mysql_error());
$query = "SELECT sector FROM Main_table ";
$result = mysqli_query($link, $query);
while($row = mysqli_fetch_assoc($result)) {
$options .= "<option value=\"".$row['sector']."\">".$row['sector']."</option>\n ";
}
echo $options;
?>
subsector_options.php shown below:
<?php
$link = mysqli_connect("********", "*****,"*******", "********") or die (mysql_error());
$Sectors = $_REQUEST['filter_sector'];
$query = "SELECT sub_sector FROM Main_table WHERE sector='$Sectors'";
$result = mysqli_query($link, $query);
while($row = mysqli_fetch_assoc($result)) {$options .= "<option value=\"".$row['sub_sector']."\">".$row['sub_sector']."</option>\n ";
}
echo $options;
?>
For completeness, the solutions were:
Check how AJAX operations are doing using a browser network monitor
Load AJAX fetcher scripts in a browser tag - in many cases they will render quite happily there, allowing them to be more easily debugged
AJAX scripts that return HTML for injection should only return that HTML, and not a full HTML document.

Select * From '%item%'?

I have a drop down menu that I use to you choose from and this results in a value given to the next page. I would like to use this value to determine where to select from. So the possible values are car and toys. So I would like to let the user use the drop down menu to choose car which results in the database selecting from car to find the item.. If the user chooses toys I would have them select from toys in order to find the item. When I attempt to use this code I just get an error. If I delete '%item%' the error is gone. Any help would be loved. Thanks.
Submitting
<form action="search.php" method="post">
<select>
<option value>Choose A Item</option>
<option value="car" name="item">Car</option>
<option value="toys" name="item">Toys</option>
</select>
<input type="submit" name="submit" value="Submit" />
</form>
Searching
$term = $_POST['term'];
$item = $_POST['item'];
$query = mysql_query("select * from '%$item%' where Items like '%$term%'");
if(mysql_num_rows($query) <= 0)
{
echo "<center>No results. Please try another item.</center>";
} else {
while ($row = mysql_fetch_array($query)) {
echo "<p2>";
echo $row['Items'], ' - Location ' .$row['Loc'];
echo '<br/><br/>';
echo "</p2>";
}
}
?>
1.) - don't use mysql_query - its an outdated library and your query as written above is subject to SQL injection - the most common compromise on the internet.
2.) don't use like '%...%' as this can't be indexed and will be horribly slow on any medium size table or greater. try to at least remove the first % to allow indexing.
http://php.net/manual/en/book.pdo.php
I think your query should be changed into: $query = mysql_query("select * from '$item' where Items like '%$term%'");

Categories