Get value from MySQL database and populate dropdown box [duplicate] - php

This question already has answers here:
Using PHP to populate a <select></select> dropdown? [duplicate]
(7 answers)
Closed 7 months ago.
I hope someone can help me figure this out as I'm new to PHP and MySQL. But basically, what I'm trying to do is to pull the data from the database and populate the dropdown box and textbox, and so I can update the value in the textbox.
This is the table structure:
id | hf_name | hf_price
------------------------
AI | test 1 | 123
AI | test 2 | 123
So let's say I wanna update "test 1" price, I would select "test 1" in the dropdown selection and update the price in the textbook.
This are my code:
<form class='data_form' action='data/food_update.inc.php' method='post'>
<select>
<?php while ($row = mysqli_fetch_array($result)):; ?>
<option><?php echo $row[1];?></option>
<?php endwhile;?>
</select>
<input type='number' name='hf_price' placeholder='$'>
<button type='submit'>UPDATE</button>
</form>
Include:
<?php
//CONNECTION TO MySQL
include '../dbh.php';
//VARIABLES
$hf_name = $_POST['hf_name'];
$hf_price = $_POST['hf_price'];
$by_user = $_SESSION['Fname'];
$up_date = date('Y-m-d');
$sql = "SELECT hf_name FROM hotfoods";
$result = mysql_query($conn, $sql);
?>
Thanks!

Try changing the option to
<option value="<?php echo $row[2];?>"><?php echo $row[1];?></option>
Where I'm assuming $row[2] variable contains the hf_price value.

$query = "select * from tablename";
$result = mysqli_query($query);
<select>
<?php
while($row = mysqli_fetch_assoc($result){
?>
<option value='<?php echo $row['hf_name']; ?>'><?php echo $row['hf_name']; ?></option>
<?php
}
?>
</select>

but for this you need to change your id datatype into int,
$query = "select * from tablename";
$result = mysqli_query();
<select id="nameID" name="hf_name">
<?php
while($row = mysqli_fetch_assoc($result){
?>
<option value='<?php echo $row['id']; ?>'><?php echo $row['hf_name']; ?></option>
<?php
}
?>
</select>
This will be fine when you fetch details but it does not update any value because for this you need to use Ajax or Jquery for update on Select, let me to try it.
Ajax
$("#nameID").onchange(function(){
var id = $("#id").val();
$.ajax(
url: "update.php",
type: "POST",
data: {'id'=id},
success: function(){
alert("ok");
});
});
Try this it might work.

You should assign a name attribute value (in this case, hf_name) on select element so that that become available in $_POST array.
<form class='data_form' action='data/food_update.inc.php' method='post'>
<select name="hf_name">
<?php while ($row = mysqli_fetch_array($result)):; ?>
<option value="<?php echo $row['hf_name']?>"><?php echo $row['hf_name'];?></option>
<?php endwhile;?>
</select>
<input type='number' name='hf_price' placeholder='$'>
<button type='submit'>UPDATE</button>
</form>
Now this is on which the form will be submitted. Where you can take user's submitted data through $_POST array.
<?php
//CONNECTION TO MySQL
include '../dbh.php';
//VARIABLES
$hf_name = $_POST['hf_name'];
$hf_price = $_POST['hf_price'];
$query = sprintf("UPDATE hotfoods SET hf_price='%d' WHERE hf_name='%s'",
mysql_real_escape_string($hf_price),
mysql_real_escape_string($hf_name));
$result = mysql_query($conn, $query);
if ($result) {
echo 'Price updated!';
} else {
echo 'Problem while updating price';
}
?>

Related

How to call select tag id in another select tag in php

I have created a form in that form I want that if the user selects one element from select tag then select tag 2 should enable and shows the value related to that element.
<form action="filename.php" method="post" enctype="multipart/form-data" >
<?php while($row =mysqli_fetch_array($result)) {?>
Artist: <?php echo $row['artist'];?>
<select name="to_artist" id = "to_artist" class="form-control">
<option value="<?php echo $row['artist'];?>">Select If you want to change</option>
<?php
$sql1 = mysqli_query($con, "SELECT DISTINCT artist_name FROM album");
$row1 = mysqli_num_rows($sql);
while ($row1 = mysqli_fetch_array($sql1)){
echo "<option value='". $row1['artist_name'] ."'>" .$row1['artist_name'] ."</option>" ;
}
?>
</select>
Album : <?php echo $row['album_name'];?>
<select name="to_album" id = "to_album" class="form-control">
<option value="<?php echo $row['album_name'];?>">Select If you want to change</option>
<?php
$artistname=$_POST['to_artist'];
$sql2 = mysqli_query($con, "SELECT * FROM album where artist_name='$artistname'");
$row2 = mysqli_num_rows($sql2);
while ($row2 = mysqli_fetch_array($sql2)){
echo "<option value='". $row2['album_name'] ."'>" .$row2['album_name'] ."</option>" ;
}
?>
</select>
<?php }?>
<input type="Submit" value="Submit" name="save" id="save"/>
</form>
In this code, I want that if the user selects an artist name then related to that artist albums will be shown in another select tag can anyone help me?
I recommend to use jquery for that and make an ajax call to php. For example
<script>
$("#to_artist").change(function () {
var selected_artist= $("#to_artist option:selected").val();
$.ajax({
url: "phpfile.php",
type: "POST",
data:{artist:selected_artist},
success: function (response) {
//here append response to select box.
}
});
});
</script>
<?php
if(isset($_POST['artist'])){
$artistname=$_POST['artist'];
//here your query to get albums for the selected artist and return them.
$sql2 = mysqli_query($con, "SELECT * FROM album where artist_name='$artistname'");
$row2 = mysqli_num_rows($sql2);
while ($row2 = mysqli_fetch_array($sql2)){
echo "<option value='". $row2['album_name'] ."'>" .$row2['album_name'] ."</option>" ;
}
}
?>
//you can create a div inside select box where you would like to append options.
Ex.
<select>
<div id="appended-options">
</div>
</select>
use this in jquery : $("#appended-options").append(response);

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.

select tag not passing value to PHP code

I have 2 PHP files.
File1: A form to select skills from an existing table (Skills table with column name: skill & skill_id)
<select name="skill1">
<?php
$self=$_SESSION['subuser_id'];
$sql = "SELECT * FROM skills";
$result = mysqli_query($conn, $sql);
while($row = mysqli_fetch_assoc($result))
{
$skill = $row["skill"];
$skill_id= $row["skill_id"];
?>
<option value='<?php $skill_id?>'><?php echo $skill;?></option>
<?php
}
?>
</select>
File2: I am recalling value through $skill1 =$_POST['skill1']; which is returning null.
I want to pass skill_id of the selected skill in code 1 to $skill1 variable on file2
Change
<option value='<?php $skill_id?>'><?php echo $skill;?></option>
to
<option value='<?php ECHO $skill_id;?>'><?php echo $skill;?></o

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.

Categories