HTML select from mysql based on previous select - php

I am currently building a website. I want to implement a feature with 3 HTML select fields.
city
street
building
I was able to achieve full fetch of all distinct cities, streets and buildings. However, that is not exactly what I need, since they are all shuffled and you can't really see if a certain city has a certain street or not.
Here is the algorithm I have in mind:
Pre-requisite: All dropdowns besides city are disabled and are only enabled upon dropdown above selection.
Step 1: User selects city via dropdown
Step 2: All streets of that city are then fetched from MySQL into the street dropdown and it is now enabled.
Step 3: User selects street via dropdown
Step 4: All buildings of that street are then fetched from MySQL into the building dropdown and it is now enabled.
I am very new to website development, so please bear with me here and if possible - point me in the right direction.
My current implementation:
<select name="city">
<?php
if ($result = mysqli_query($conn, $queryCity)) {
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_array($result)) {
echo "<option value='" . $row['city'] . "'>" . $row['city'] . "</option>";
$selected = $row['city'];
}
}
}
?>
</select>
<select name="street">
<?php
if ($result = mysqli_query($conn, $queryStreet)) {
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_array($result)) {
echo "<option value='" . $row['city'] . "'>" . $row['city'] . "</option>";
$selected = $row['city'];
}
}
}
?>
</select>
<select name="building">
<?php
if ($result = mysqli_query($conn, $queryBuilding)) {
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_array($result)) {
echo "<option value='" . $row['city'] . "'>" . $row['city'] . "</option>";
$selected = $row['city'];
}
}
}
?>
</select>

Your algorithm could work like that.
But you may need to reload the page or fetch the content with a asynchronous request (for example AJAX) if the user selected a city. You could pass the city as a GET- or POST-Parameter, and if that Parameter is set search for the streets and enable the dropdown, else just disable the dropwdown menu. The same applies for the buildings.
And please use Prepared Statements instead of normal queries when using a query with user input, you don't want to get visited by Little Bobby Tables ;)

I have found a solution to this and it is quite simple.
.js:
function getBuildings() {
let street = document.getElementById("street").value;
let ajax = new XMLHttpRequest();
let method = "POST";
let url = "get_buildings_of_street.php";
let asynchronous = true;
const obj = {};
obj.street = street;
ajax.open(method, url, asynchronous);
ajax.setRequestHeader("Content-type", "application/json");
ajax.onreadystatechange = function () {
if (this.readyState === 4 && this.status === 200) {
let data = JSON.parse(this.responseText);
let html = "<select>";
html += "<option value='" + "-" + "'>" + "-" + "</option>";
for (let a = 0; a < data.length; a++) {
html += "<option value='" + data[a] + "'>";
html += data[a];
html += "</option>";
}
html += "</select>";
document.getElementById("building").innerHTML = html;
}
}
ajax.send(JSON.stringify(obj));
}

Related

Why isn't my AJAX loading onto my webpage?

I've set up JavaScript and AJAX that's supposed to fetch data from a database subject to a set of filters, and return a table of results that match those filters. I thought I had the code set up correctly, but when I submit the search filter form, the page reloads and nothing else happens. I can't work out where I'm going wrong!
connection.php is just a file containing my database details/username/password, and I know that's working correctly. I've scoured through for syntax errors and can't find any, so it must be something to do with the way I've written my code. However, I'm very new to all this so am really struggling to see what exactly I've done wrong. Any help would be hugely appreciated!
my javascript:
function showStock(search, genre, publisher, minyear, maxyear) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("results").innerHTML = this.responseText;
}
xmlhttp.open("GET", "stock.php?search=" + search + "&genre=" + genre + "&publisher=" + publisher +
"&min-year=" + min - year + "&max-year=" + max - year, true);
xmlhttp.send();
}
}
my filter form:
<form id="filters">
<label> Search by Title:</label><br>
<input type="search" name="search">
<label>Genre:</label><br>
<select name='genre'>
<option value='All'> All </option>
<?php
function dropdownOptions($category) {
require('connection.php');
$sql = "SELECT DISTINCT ".$category." FROM stock";
$result = $conn->query($sql);
while($row = $result->fetch_assoc()) {
echo "<option value='" . $row[$category] . "'>" . $row[$category] . "</option>";
}
}
dropdownOptions("genre");
?>
</select>
<label>Publisher:</label><br>
<select name="publisher">
<option value="all"> All</option>
<?php
dropdownOptions("publisher");
?>
</select>
<div class="year">
<label>Release Year:</label><br>
<input type="number" name="min-year" min="1970" max="2018">
<label> to </label>
<input type="number" name="max-year" min="1970" max="2018">
</div>
<div class="buttons">
<button type="submit" onclick="showStock(search, genre, publisher, min-year, max-year)">SEARCH</button>
<button type="reset">CLEAR</button>
</div>
</form>
my stock.php code:
<?php
require('connection.php');
$search = $_GET['search'];
$publisher = $_GET['publisher'];
$genre = $_GET['genre'];
$minyear = intval($_GET['min-year']);
$maxyear = intval($_GET['max-year']);
if ($search == "") {
$searchQ = "";
} else {
$searchQ = "AND CONTAINS(title, $title) ";
}
if ($genre == "all") {
$genreQ = "";
} else {
$genreQ = "AND genre = $genre ";
}
if ($publisher == "all") {
$publisherQ = "";
} else {
$publisherQ = "AND publisher = $publisher ";
}
if ($minyear == "" && $maxyear == "") {
$yearQ = "";
} else if ($minyear == "" && $maxyear != "") {
$yearQ = "AND release_date <= $maxyear ";
} else if($minyear != "" && $maxyear == "") {
$yearQ = "AND release_date >= $minyear ";
} else if ($minyear != "" && $maxyear != ""){
$yearQ = "AND release_date BETWEEN $minyear AND $maxyear ";
}
$sql = "SELECT * FROM stock WHERE id > 0".$searchQ.$genreQ.$publisherQ.$yearQ.";";
$result = $conn->query($sql);
echo "<table>
<tr>
<th>ID</th>
<th>Title</th>
<th>Publisher</th>
<th>Genre</th>
<th>Price</th>
<th>Release Year</th>
<th>Stock Units</th>
</tr>";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['title'] . "</td>";
echo "<td>" . $row['publisher'] . "</td>";
echo "<td>" . $row['Hometown'] . "</td>";
echo "<td>" . $row['genre'] . "</td>";
echo "<td>" . $row['price'] . "</td>";
echo "<td>" . $row['release_date'] . "</td>";
echo "<td>" . $row['stock_units'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
I expected a table of relevant results to load on my webpage (hosted on my uni server here: https://students.emps.ex.ac.uk/admt201/webdev/stock-lookup.php), but instead all that happens is that my search parameters are added to the url of the original webpage and nothing new loads.
This is not an answer, but a long comment with multiple suggestions.
A problem of this nature is best attacked by breaking it down and confirming each part. Since PHP is notoriously difficult to troubleshoot (since if there is an error it doesn't generate any helpful message it just abends) I suggest you tackle the PHP side first.
So, make a copy of your stock.php file and replace the $_GET[] variable assignments with some hard-coded data. Then, make sure it outputs success messages (to ensure you are receiving the data you expected) and run that modified stock.php file as a stand-alone. You first need to confirm that the PHP is working, because if it isn't you can troubleshoot the javascript side till the cows come home and true happiness will continue to elude you.
Another troubleshooting methodology that is useful when troubleshooting PHP is to simply add a number of file writes throughout the file, like this:
$hF = fopen("__debug.log", "a");
//run a couple lines of code
fwrite($hF, "Got to here 01");
//run a few more lines of code
fwrite($hF, "Got to here 02");
//repeat...
Then, check the created __debug.log file and see if you got all of the expected file writes, or if the code died somewhere along the way. Otherwise, how would you know?
Note that there is an extension for Chrome called PHPConsole that allows you to output console messages to the browser, but it can be a bit tricky to get working off the start -- whereas the above fwrite() method is rock-solid-reliable and easily implemented.
Similarly, on the javascript side, salt your code with a bunch of console.log() statements to identify where the problems are manifesting.

Set previously selected value in Dropdown box using PHP

So, what I'm trying to achieve that after the user hits submit, the dropdown retains the value that the user have chosen. This is my code for the dropdown, I understand that I have to selected = 'selected', but I couldn't figure out how it fits in my code.
if (mysqli_num_rows($result) > 0) { // output data of each row
while($row_branch = mysqli_fetch_array($result)) {
$menu_branch .= "<option value='".$row_branch["0"]."'>" .
$row_branch["0"]. "</option>";
}
}
echo $menu_branch;
You cannot just add selected = selected inside the loop because every option will be selected.
You might need the if statement to select the option of your choice.
For example:
if($row_branch["0"] == 'bar'){
$menu_branch .= "<option value='".$row_branch["0"]."' selected>" .
$row_branch["0"]. "</option>";
}else{
$menu_branch .= "<option value='".$row_branch["0"]."'>" .
$row_branch["0"]. "</option>";
}
When the user select an option, Where you submit this information?
If this information return from a database
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row_branch = mysqli_fetch_array($result)) {
$select = ($row_branch["0"]==$value_db)? "selected='selected'" : "";
$menu_branch .= "<option value='".$row_branch["0"]."' $select>" .
$row_branch["0"]. "</option>";
}
}
if i understand right:
// $yourvalue is previous dropdown value
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row_branch = mysqli_fetch_array($result)) {
if ($row_branch["0"] == $yourvalue)
$selected = "selected";
else
$selected = "";
$menu_branch .= "<option value='".$row_branch["0"]."' $selected>" .
$row_branch["0"]. "</option>";
}
}
echo $menu_branch;

Getting the drop-down menu selected item and using it in php

I have the following drop-down list that fetches a list coalitions from the database (this list is populated as expected)
<form style = "display: inline-block;" >
<select class="form-control" name ="coalition_select" onchange = "showCandidates(this.value)" method="GET">
<option id = "coalition_id" value="coalition">Coalitions</option>
<?php
include_once 'connection.php';
$sql_coalition = mysqli_query($conn, "SELECT coalition FROM candidates");
while ($row = $sql_coalition->fetch_assoc()) {
echo "<option value=\"coalition\">" . $row['coalition'] . "</option>";
}
?>
</select>
</form>
The problem begins here. Here I'm trying to first get the selected value (which is on of the coalitions) from the drop-down list and second use the value to display users with similar coalition attribute.
here is the script to get the value from the drop-down:
<script>
function showCandidates (str) {
if (str.length == "") {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint").innerHTML = this.responseText;
}
};
xmlhttp.open("GET","includes/admin.users.list.inc.php?q="+str,true);
xmlhttp.send();
}
}
</script>
and here is the admin.users.list.inc.php file
<body>
<?php
$q = $_GET['q'];
$conn = mysqli_connect('localhost','root','','voting');
if (!$conn) {
die('Could not connect: ' . mysqli_error($conn));
}
mysqli_select_db($conn,"osako_Voting");
$sql="SELECT * FROM candidates WHERE coalition = '".$q."'";
$result = mysqli_query($conn,$sql);
echo "<table>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Coalition</th>
<th>Email</th>
</tr>";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['firstname'] . "</td>";
echo "<td>" . $row['lastname'] . "</td>";
echo "<td>" . $row['coalition'] . "</td>";
echo "<td>" . $row['email'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($conn);
?>
</body>
The problem seem to be that I'm unable to set the variable $q so that it captures the selected value. right now as it is set it seems to capture the index instead of the value itself. How can this be correctly done? If it is of any help, I'm using this tutorial as a guideline
https://www.w3schools.com/php/php_ajax_database.asp
IN SUMMERY:
If we have a drop-down list that has been populated dynamically using php script. How can be get the selected value using ajax and use the said value in another php script.
Thanks
It seems the problem is in this row:
echo "<option value=\"coalition\">" . $row['coalition'] . "</option>";
You're passing the select value to showCandidates(), to be passed via AJAX but you're setting the option value to be always static "coalition" and not the dynamic values you're fetching from DB.
Maybe you should change the row to
echo "<option value=\"" . $row['coalition'] . "\">" . $row['coalition'] . "</option>";
your not setting value to value attribute . your just setting constant string for all option values coalition
while ($row = $sql_coalition->fetch_assoc()) {
echo "<option value=\"$row['coalition']\">" . $row['coalition'] . "</option>";
}
I know you have accepted an answer but i am puzzled as to this;
in your function you have this
document.getElementById("txtHint").innerHTML = "";
But you don't have any form element with the id "txtHint"
So what element is being sort with that ID?

MySQL Select based on drop down value

I have the following code:
<?php
session_start();
include_once("config.php");
$query = "SELECT Category FROM books";
$result = mysqli_query ($mysqli, $query);
echo '<select name="dropdown" value=""><option value="">Dropdown</option>';
while($row = mysqli_fetch_array($result))
{
echo '<option value="' . $row['Category'] . '">' . $row['Category'] . '</option>';
}
echo "</select>";
?>
the values of the drop down box are filled from the database.
I was wondering if theres a way to have a select statement that will run when a user clicks on one of the options in the drop down menu and then populate the results in a table?
any information will help!
Thanks
Ok, resontant81, you want to fill a table depending on the option selected, next code does exactly what you want, the explanation comes just after :
<html>
<head>
<title>My list</title>
<script type="text/javascript">
//----------------------------------------------------------------
// SENDS SELECTED OPTION TO RETRIEVE DATA TO FILL TABLE.
function send_option () {
var sel = document.getElementById( "my_select" );
var txt = document.getElementById( "my_option" );
txt.value = sel.options[ sel.selectedIndex ].value;
var frm = document.getElementById( "my_form" );
frm.submit();
}
//----------------------------------------------------------------
</script>
</head>
<body>
Click on any option
<br/>
<select id="my_select" onchange="send_option();">
<option>Select an option</option>
<?php
//----------------------------------------------------------------
// LIST FILLED FROM DATABASE (ALLEGEDLY).
for ( $i = 0; $i < 5; $i++ )
{ $text = chr($i+65) . chr($i+65) . chr($i+65);
echo "<option value='" . $text . "'>" . $text . "</option>";
}
//----------------------------------------------------------------
?>
</select>
<br/>
<br/>
<table>
<?php
//----------------------------------------------------------------
// TABLE FILLED FROM DATABASE ACCORDING TO SELECTED OPTION.
if ( IsSet( $_POST["my_option"] ) ) // IF USER SELECTED ANY OPTION.
for ( $i = 0; $i < 4; $i++ ) // DISPLAY ROWS.
{ echo "<tr>";
for ( $j = 0; $j < 6; $j++ ) // DISPLAY COLUMNS.
echo "<td>" . $_POST["my_option"] . "</td>"; // DISPLAY OPTION.
echo "</tr>";
}
else echo "<tr><td>Table empty</td></tr>";
//----------------------------------------------------------------
?>
</table>
<!-- FORM TO SEND THE SELECTED OPTION. -->
<form method="post" action"01.php" style="display:none" id="my_form">
<input type="text" id="my_option" name="my_option"/>
</form>
</body>
</html>
To make things easier for you (and for me), I am not using a database, all you have to do is copy-paste previous code to a text file, rename it "01.php" (because that's the action of the form, you can change it), and run it in your browser, is ready to use.
The dropdown is filled from database (in this case, with letters), when an option is selected the page reloads with the selected option and fills the table.
You said: "a select statement that will run when a user clicks on one of the options in the drop down menu and then populate the results in a table". This select statement you want you must put it right after the line :
if ( IsSet( $_POST["my_option"] ) ) // IF USER SELECTED ANY OPTION.
So your select statement will take the selected option from $_POST and use it to retrieve the right data and display it.
Let me know if it helps you.
This is the code to fill the dropdown, it's my code with yours combined:
// LIST FILLED FROM DATABASE (ALLEGEDLY).
$query = "SELECT Category FROM books";
$result = mysqli_query ($mysqli, $query);
while ( $row = mysqli_fetch_array($result) )
echo "<option value='" . $row['Category'] . "'>" . $row['Category'] . "</option>";
Next edit is to fill the table. Change the query for the right one if it's not right :
// TABLE FILLED FROM DATABASE ACCORDING TO SELECTED OPTION.
$query = "SELECT Category FROM books where category like '" . $_POST["my_option"] . "'";
$result = mysqli_query ($mysqli, $query);
while( $row = mysqli_fetch_array($result) )
echo "<tr>" .
"<td>" . $row['book_name'] . "</td>" .
"<td>" . $row['author'] . "</td>" .
"<td>" . $row['Category'] . "</td>" .
"</tr>";
I'm assuming $mysqli is your db connection and it's made through config.php. I'm also assuming that category is a column name in the books table. It is up to you to sanitize and validate the user input. This is simply an example to get you started.
page.php ....
<?php
session_start();
include_once("config.php");
function categories() {
global $mysqli;
$result = "";
$stmt = "SELECT Category FROM books GROUP BY Category";
$sql = mysqli_query ($mysqli, $stmt);
while ($row = $sql->fetch_array(MYSQLI_BOTH))
{
$result .= '<option value="' . $row['Category'] . '">' . $row['Category'] . '</option>';
}
mysqli_free_result($sql);
mysqli_close($mysqli);
return $result;
}
IF (isset($_POST['ThisForm'])) {
$category = htmlspecialchars(strip_tags(trim($_post['dropdown'])));
$stmt = "SELECT * FROM books WHERE category ='$category'";
$sql = mysqli_query ($mysqli, $stmt);
while ($row = $sql->fetch_array(MYSQLI_BOTH))
{
// do something with result
}
// free result and close connection
mysqli_free_result($sql);
mysqli_close($mysqli);
}ELSE{
// base form
echo '<form action="page.php" name="something" method="post">';
echo '<select name="dropdown" value=""><option value="">Dropdown</option>'.categories().'</select>';
echo '<input type="submit" name="ThisForm" value="submit" />';
echo '<form>';
}
?>

Variable not being passed to second select dropdown

I have two dropdowns, one displays States from HTML SELECT, and the next one populates from MYSQL query of markets matched to the state selected. After selection of the Market, the SID should appear. The problem is the code remembering the $pickstate var when you select the $market var so Mysql query can display the SID result.
<?php
// Get State from above form.
$pickstate = $_POST['state'];
$result = mysql_query("SELECT Market FROM ppc WHERE State='" . $pickstate . "'");
// After State is selected from MySQL, populate Market Dropdown.
echo '<form style="display:inline-block;" action="" method="POST"><select id="Market" name="Market" onchange="this.form.submit();">';
echo '<option value="">Select Your Market</option>';
while ($row = mysql_fetch_array($result)) {
echo ( '<option value= "' .$row['Market']. '">'.$row['Market'].'</option>' );
}
echo "</select></form><br />";
// Get SID Result
$market = $_POST['Market'];
$sid = mysql_query("SELECT SID FROM ppc WHERE State='" . $pickstate . "' AND Market='" . $market . "'");
// This is for debugging only.
// This shows, until market is selected.. then vanishes.
echo $pickstate . "<br />";
// This shows after market has been chosen.
echo $market . "<br />";
// "SHOULD" Display SID.
if ($state != null && $market != null) {
echo '<p style="display:inline-block;margin:0;padding:0;"> Use: ';
}
while ($row = mysql_fetch_array($sid)) {
echo $row['SID'] . ' ';
}
?>
it will not work like that .
the query is server side . you may consider to send your selected value to another page and then get values from your query
OR you can use ajax .

Categories