PHP/MySQL dropdowns - php

I have a main MySQL table called restaurants which holds all details for each restaurant - RestaurantID, RestaurantName, Address, Town, County etc.
I am creating a Review and ratings form in PHP to allow my users to review each of the restaurants. I have created 2 dropdown menus one which the user will select the County and the second I hope to populate with RestaurantName of those in that County.
Can anyone spot where I am going wrong? My first dropdown populates without any issues, although the second dropdown is blank?
I've added all my code so far for this, anything else that you think would be useful let me know.
leave.php
<?php
include_once "settings.php"
?>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<body>
<div class="County">
<label>County</label>
<select name = "County" onchange="getId(this.value);">
<option value ="">Select County </option>
<?php
$query = "SELECT DISTINCT County FROM restaurants";
$results = mysqli_query($con, $query);
foreach ($results as $restaurants) {
?>
<option value ="<?php echo $restaurants['County']; ?>"><?php echo $restaurants["County"]; ?></option>
<?php
}
?>
</select>
</div>
<div class="RestName">
<label>Restaurant</label>
<select name = "Restaurant" id="RestList">
<option value ="">Select Restaurant </option>
<option value="" >
<?php
include_once "settings.php";
if (!empty($_POST["RestaurantID"])) {
$RestaurantID = $_POST["RestaurantID"];
$query = "SELECT * FROM restaurants WHERE RestaurantID = $RestaurantID";
$results = mysqli_query($con, $query);
foreach ($results as $County) {
?>
<option value="<?php echo $restaurants["RestaurantID"]; ?>"><?php echo $restaurants["RestaurantName"]; ?>"></option>
<?php
}
}
?>
</select>
</div>
<script>
function getId(val){
$.ajax({
type: "POST",
url:"getdata.php",
data: "RestaurantID="+val,
success: function(data){
$("#RestList").html(data);
}
});
}
</script>
</body>
</html>
getdata.php
<?php
include_once "settings.php";
if (!empty($_POST["RestaurantID"])) {
$RestaurantID = $_POST["RestaurantID"];
$query = "SELECT * FROM restaurants WHERE RestaurantID = $RestaurantID";
$results =
($con, $query);
foreach ($results as $restaurants) {
?>
<option value="<?php echo $restaurants['RestaurantID']; ?>"><?php echo $restaurants["RestaurantName"]; ?>"></option>
<?php
}
}
?>

In this line:
<select name="Restaurant" id="RestList" </select>
You don't actually close the "<select>" tag...

Related

Populating Second Dropdown Based on first dropdown from the database table without using javascript

I am trying to create a form for the admin of an e-commerce site and the admin should be able to create a category and add new products.
I have two tables in my database from where I want to populate the dropdown list. I want the second dropdown to populate as I select the first drop-down value but I have to do it without the submit button.
This is the code for the form with two drop-downs:-
<form method="post" action="add_category.php">
<h4>Choose the root level:</h4>
<select name="rootLevel">
<?php
$conn = mysqli_connect("localhost","root","","store")
or die("Error in Connection on add_category");
$query = "SELECT * FROM root_category";
$result = mysqli_query($conn,$query) or die("Query failed add_category");
$id=1;
//echo $id;
//echo "Hello";
while($row = mysqli_fetch_assoc($result)){
global $id;
//echo "<h1>$id</h1>";
$id = $row['id'];
echo "<option name='rootLevel' value=$id>".$row['Name']."</option>";
//echo "<option>$id</option>";
}
?>
</select>
<br><br>
<h4>Choose the Level 1 Category:</h4>
<select name="level1">
<?php
global $id;
//echo "<option>".$_POST['rootLevel']."</option>";
$query_level1 = "Select * from level1_category Where P_id = $id";
$result1 = mysqli_query($conn,$query_level1) or die("Query failed level 1");
while($row = mysqli_fetch_assoc($result1)){
$id1 = $row['P_id'];
echo "<option name='level1' value=$id1>".$row['Name']."</option>";
}
?>
</select>
I have successfully populated the first drop-down and now I want to fetch the $id in 'resultValue' without the submit button.
You cant do this only with PHP. You have to use jquery OR Ajax to do this.
Please check this example page . This may help you
https://www.tutorialrepublic.com/faq/populate-state-dropdown-based-on-selection-in-country-dropdown-using-jquery.php
OR
https://www.codexworld.com/dynamic-dependent-select-box-using-jquery-ajax-php/
<head>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script>
$(document).ready(function(){
$("select.country").change(function(){
var selectedCountry = $(".country option:selected").val();
$.ajax({
type: "POST",
url: "states.php",
data: { country : selectedCountry }
}).done(function(data){
$("#states").html(data);
});
});
});
</script>
</head>
<body>
<div class="form-group">
<label for="country" class="input__label">Country</label>
<select id="country" onchange="states(this.value);" name="country" class="country form-control login_text_field_bg input-style">
<option selected>Choose...</option>
<?php
$sql= $cnn->prepare("SELECT key_iso_code FROM country");
$sql->execute();
while($i = $sql-> fetch($cnn::FETCH_ASSOC)){
extract($i);
?>
<option><?php echo $key_iso_code ?></option>
<?php
}
?>
</select>
</div>
<div class="form-group col-md-4">
<label for="inputState" class="input__label">State/Province</label>
<select id="states" name="state" class="form-control input-style">
<option selected>Choose...</option>
</select>
</div>
</body>
<?php
include("PDOConnection.php");
if(isset($_POST["country"])){
// Capture selected country
$country = $_POST["country"];
// Display city dropdown based on country name
if($country !== 'Shoose...'){
$sql= $cnn->prepare("SELECT state.key_name FROM country INNER JOIN state ON country.key_id = state.key_country_id WHERE country.key_iso_code like '$country'");
$sql->execute();
while($i = $sql-> fetch($cnn::FETCH_ASSOC)){
extract($i);
echo "<option>". $key_name . "</option>";
}
}
}
?>

Retrieve and display text from multiple dropdown menus without reloading page

I am learning PHP, Jquery, Ajax and other web dev languages and have been stuck on this problem for hours on end.
I have two drop-down boxes:
One displaying a list of countries (via a database query)
One displaying a list of cities related to the country chosen (also via a database query)
Anyway, I want to be able to retrieve the text of both menu boxes and use them in further database queries in a text box on the same page at the click of a button but with no reloading of the page involved.
I have used JQuery and Ajax for the dynamic menu so I have some idea of what is required for this task. Here is the code for the page in question:
<body>
<div class = "country">
<label>Select a Country: </label>
<select name="country" onchange="getId(this.value);">
<option value = "">Select Country</option>
<?php
$query = "SELECT DISTINCT(Country) AS Country FROM Locations ORDER BY Country ASC;";
$results = mysqli_query($con, $query);
foreach ($results as $country) {
?>
<option value = "<?php echo $country['Country']; ?>"><?php echo
$country['Country'] ?></option>
<?php
}
?>
</select>
</div>
</br>
<div class="city">
<label>Select a City: </label>
<select name="city" id="cityList">
<option value="">Select a city</option>
</select>
</div>
<script src="https://code.jquery.com/jquery-1.12.0.min.js"></script>
<script>
function getId(value){
$.ajax({
type: "POST",
url: "getdata.php",
data: "Country="+value,
success: function(data){
$("#cityList").html(data);
}
});
}
</script>
<button id="button">Go</button>
document.getElementById("button").onclick = function(){
document.getElementById("textbox").innerHTML = "<?php $query = mysqli_query($con, "SELECT * FROM Locations WHERE Country='dropdown text' AND City='dropdown text'");
while($results = mysqli_fetch_array($query)){
echo "Name: " . "$results['City']" . "is in" . "$results['Country']" "</option>";
}
?>";
}
</script>
</body>
The PHP file I have been working on so far is incomplete as I am unsure on how to echo the result, since I want it to eventually end up in the text box on the main page. My PHP is as follows:
<?php
include_once "connection.php";
if(!empty($_POST['Country'])||($_POST['City'])){
$country = $_POST['Country'];
$city = "SELECT * FROM Locations WHERE Country = '$Country' AND City = '$city'";
$results = mysqli_query($con, $query);
foreach ($results as $city) {
?>
<option value = "<?php echo $city['Country']; ?>"><?php echo $city['City'] ?></option>
<?php
}
}
?>
Any suggestions or advice would be greatly appreciated.
<?php
include_once "connection.php";
if(!empty($_POST['Country'])){
$country = $_POST['Country'];
$city = "SELECT * FROM Locations WHERE Country = '$Country' ";
$results = mysqli_query($con, $query);
foreach ($results as $city) {
?>
<option value = "<?php echo $city['City']; ?>"><?php echo $city['City'] ?></option>
<?php
}
}
?>
You are posting just 'Country' and have to get just 'country' from post. the city does not come from post.

Save ID from dropdown list into other table

I have a form with fields and one dropdown list. The data from the dropdown list comes out the table: categorie. (fields are: catID, catName)
When I select a categorie from the drop down list and fill all the other input fields, it saves all the input fields and only the catName from the categorie table into the tabel: event.
How can I also save the selected catID from the categorie table into the event table?
Can someone helm me out here?
Regards, Benny
<?php require '../Connections/localhost.php'; ?>
<?php
if(isset($_POST['newEvent'])) {
session_start();
$eventName = $_POST['SelCatName'];
$eventSDate = $_POST['Event-StartDate'];
$eventSTime = $_POST['Event-StartTime'];
$eventEDate = $_POST['Event-EndDate'];
$eventETime = $_POST['Event-EndTime'];
$eventDescription = $_POST['Event-Description'];
$catID = $_POST["catID"];
$sql = $con->query("INSERT INTO event (eventName, eventSDate, eventSTime, eventEDate, eventETime, eventDescription, catID)Values('{$eventName}', '{$eventSDate}', '{$eventSTime}', '{$eventEDate}', '{$eventETime}', '{$eventDescription}', '{$catID}')");
header('Location: eventOK.php');
}
?>
<form action="" method="post" name="RegisterForm" id="RegisterForm">
<div class="FormElement">
<select name="SelCatName" class="TField" id="SelCatName">
<option selected="selected" id="0">--Selecteer een categorie--</option>
<?php
$GetAllCategories = $con->query("SELECT * FROM categorie");
while ($ViewAllCategories = mysqli_fetch_array($GetAllCategories)){
?>
<option id="<?php echo $ViewAllCategories['catID']; ?>"><?php echo $ViewAllCategories ['catName']; ?> </option>
<?php } ?>
</select>
You made a mistake in <option id="id"></option>
if you wanna take value from select child.
you must change id to value="" or you must add value="id" proper.
change your select box block completely like below..
<select name="SelCatName" class="TField" id="SelCatName">
<option selected="selected" id="0">--Selecteer een categorie--</option>
<?php
$GetAllCategories = $con->query("SELECT * FROM categorie");
while ($ViewAllCategories = mysqli_fetch_array($GetAllCategories)){
?>
<option value="<?PHP echo $ViewAllCategories['catID'].'-'.$ViewAllCategories['catName']; ?>"> <?PHP echo $ViewAllCategories['catName']; ?></option>
<?php } ?>
</select>
and a tip for mysql query... to the best of one's ability don't use "select * from" use it if you dont need to all colums better than "*"
$con->query("SELECT catID, catName FROM categorie");
PHP file
<?php require '../Connections/localhost.php'; ?>
<?php
if(isset($_POST['newEvent'])) {
session_start();
//$eventName = $_POST['SelCatName'];
$eventSDate = $_POST['Event-StartDate'];
$eventSTime = $_POST['Event-StartTime'];
$eventEDate = $_POST['Event-EndDate'];
$eventETime = $_POST['Event-EndTime'];
$eventDescription = $_POST['Event-Description'];
$catIDs = $_POST["SelCatName"];
$catID = explode("-", $catIDs);
$sql = $con->query("INSERT INTO event (eventName, eventSDate, eventSTime, eventEDate, eventETime, eventDescription, catID)Values('{$catID[1]}', '{$eventSDate}', '{$eventSTime}', '{$eventEDate}', '{$eventETime}', '{$eventDescription}', '{$catID[0]}')");
header('Location: eventOK.php');
}
?>
to me you are missusing the attribute of ID, Replace the ID for value: your option tag already have the id and name
<select name="SelCatName" class="TField" id="SelCatName">
your code will be:
<?php
$GetAllCategories = $con->query("SELECT * FROM categorie");
while ($ViewAllCategories = mysqli_fetch_array($GetAllCategories)){
?>
<option value="<?php echo $ViewAllCategories['catID']; ?>"> <?php echo $ViewAllCategories ['catName']; ?> </option>
<?php } ?>
Therefore you will find your post as only SelCatName = (numerical ID)
Now, if you need that the list of the catID and catName stores to the next page you can re-run your query in the next page and store them in an array.

how to fetch the other values in the database equivalent to the selected dropdown item

This is my working code that fetches the data of the id_no in the database. Now, what I want is when I selected a specific id_no the name of the person owning that id_no will automatically be printed. :
<?php
$sql = "SELECT id_no from employee ORDER BY id_no asc";
$result = $conn->query($sql);
?>
<select name='id_no'>
<?php while ($row = $result->fetch_array()) { ?>
<option value="id_no" > <?php echo($row['id_no']); ?> </option>
<?php } ?>
</select>
Thanks so much!
this code will display the selected value. try this
<?php
$sql = "SELECT id_no from employee ORDER BY id_no asc";
$result = $conn->query($sql);
?>
<select name='id_no' onchange="changeSelect(this.value)">
<?php while ($row = $result->fetch_array()) { ?>
<option value="<?php echo($row['id_no']); ?>" >
<?php echo($row['id_no']); ?>
</option>
<?php } ?>
</select>
<div id="demo"></div>
<input type="text" id="text-input" />
<script>
function changeSelect(value)
{
document.getElementById("demo").innerHTML = value;
document.getElementById("text-input").value = value;
}
</script>

i am trying to display productname from newproduct mysql table into combobox. The following code is executing but its displaying a blank

**<html>
<body>
<form name="call">
<select name="category">
<option>Select a category</option>
<?php
mysql_connect("localhost","root","");
mysql_select_db("shenvel");
$category = "SELECT productname FROM newproduct";
//retrieving product name alone from newproduct
$query_result = mysql_query($category);
while($result = mysql_fetch_assoc($query_result))
{
?>
<option value = "<?php echo $result['productname']?>"><?php echo $result['productname']?></option>
//the above code displays the combo box with one empty space as output.
**
change fetch records using mysql_fetch_array()
while($result = mysql_fetch_array($query_result))
{
*********
}
And try it..
Try this
<select name="category">
<option>Select a category</option>
<?php
mysql_connect("localhost","root","");
mysql_select_db("shenvel");
$category = "SELECT productname FROM newproduct";
$query_result = mysql_query($category);
while($result = mysql_fetch_array($query_result))
{
?>
<option value = "<?php echo $result['productname']; ?>"><?php echo $result['productname']; ?></option>
<?php
}
?>
</select>
try this:
<html>
<body>
<form name="call">
<select name="category">
<option>Select a category</option>
<?php
mysql_connect("localhost","root","");
mysql_select_db("shenvel");
$category = "SELECT productname FROM newproduct";
//retrieving product name alone from newproduct
$query_result = mysql_query($category);
while($result = mysql_fetch_array($query_result))
{
?>
<option value = "<?php echo $result['productname']?>"><?php echo $result['productname']?></option>
Your while loop is being fully executed in the first <?php ... ?> snippet. The syntax you used for your while loop will not execute across multiple php code snippets.
Try echoing out your option HTML code and thus having only one php code snippet.
<html>
<body>
<form name="call">
<select name="category">
<option>Select a category</option>
<?php
mysql_connect("localhost","root","");
mysql_select_db("shenvel");
$category = "SELECT productname FROM newproduct";
//retrieving product name alone from newproduct
$query_result = mysql_query($category);
while ($result = mysql_fetch_assoc($query_result)) {
echo '<option value = "', $result['productname'], '">', $result['productname'], '</option>';
}
?>

Categories