I have this select box that populates from MySQL Data using PHP
<select>
<?php
$stmt = $pdo_conn->prepare("SELECT * from prices ");
$stmt->execute(array());
$records = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach($records as $result2) {
echo '<option value="'.$result2["product"].'">'.$result2["product"].'</option>';
}
?>
</select>
in the same table in MySQL (prices) there is a retail column, how can i put the value of retail into a text input
<input type="text" name="unitprice" />
based on the selected row in the select box?
I'd recommend using JavaScript.
Option 1
I would convert your results into a JSON Array and echo it to JavaScript. This way all information gets given the user.
<select id="mySelectBox" onchange="changeValue(this.value);">
<?php
$json_array = array();
$stmt = $pdo_conn->prepare("SELECT * from prices ");
$stmt->execute(array());
$records = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach($records as $result2) {
$product = $result2["product"];
$json_array[$product] = $result2['unitprice'];
echo '<option value="'.$result2["product"].'">'.$result2["product"].'</option>';
}
json_encode($json_array, JSON_FORCE_OBJECT);
?>
</select>
<input type="text" id="unitPrice" name="unitprice" />
<script>
var json = <?php echo $json_array; ?>;
function changeValue(myValue) {
document.getElementById("unitPrice").value = json[myValue];
}
</script>
Related
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>";
}
}
}
?>
I am trying to populate the options in my html website with information from a database but it does not populate.
All my other entries such as name, last name and address work but this is not working for me. It does not output the firstName values.
<select name="text" id="firstName">
<?php
$sql = "SELECT firstName from Members";
$results = mysql_query($sql);
while ($rows = mysql_fetch_assoc($results)){
?>
<option value="<?php echo $rows['firstName'];?>"><?php echo $rows['firstName'];?></option>
<?php
}
?>
</select>
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';
}
?>
I have two dropdowns which values are populated from MySQL. The second dropdown values depends on the first dropdown option.
Anyways, the code is working. Now using my code I am posting hospital_id to another php. But I want to display hospital_name as text on the dropdown as well, but as of now I am only able to display the hospital_id.
Please see me code below and suggest me a solution:
$query = "SELECT bp_id,bp_name FROM mfb_billing";
$result = $db->query($query);
while($row = $result->fetch_assoc()){
$categories[] = array("bp_id" => $row['bp_id'], "val" => $row['bp_name']);
}
$query = "SELECT bp_id, hospital_id, hospital_name FROM mfb_hospital";
$result = $db->query($query);
while($row = $result->fetch_assoc()){
$subcats[$row['bp_id']][] = array("bp_id" => $row['bp_id'], "val" => $row['hospital_id']);
}
$jsonCats = json_encode($categories);
$jsonSubCats = json_encode($subcats);
This is the script:
<script type='text/javascript'>
<?php
echo "var categories = $jsonCats; \n";
echo "var subcats = $jsonSubCats; \n";
?>
function loadCategories(){
var select = document.getElementById("categoriesSelect");
select.onchange = updateSubCats;
for(var i = 1; i < categories.length; i++){
select.options[i] = new Option(categories[i].val,categories[i].bp_id);
}
}
function updateSubCats(){
var catSelect = this;
var catid = this.value;
var subcatSelect = document.getElementById("subcatsSelect");
subcatSelect.options.length = 0; //delete all options if any present
for(var i = 0; i < subcats[catid].length; i++){
subcatSelect.options[i] = new Option(subcats[catid][i].val,subcats[catid][i].hosp);
}
}
</script>
This is my form:
<body onload='loadCategories()'>
<form id="reportvalue" action="testpj2.php" method="post">
<select id='categoriesSelect'>
<option value="1">Select Billing Provider</option>
</select>
<select name='hospitalname[]' id='subcatsSelect' multiple='multiple'>
<option value="all">Select Billing Provider</option>
</select>
<label for="from">From</label>
<input type="text" id="from" name="from">
<label for="to">to</label>
<input type="text" id="to" name="to">
<?php
//$a = $_REQUEST['hospitalname[]'];
//echo $a;
?>
<input type="submit" name="Submit" value="Submit">
</form>
HTML
<select id="someId"></select>
Javascript
document.getElementById('someId').innerHTML="
<option value='value1'>"+option1+"</option>
<option value='value2'>"+option2+"</option>
<option value='value3'>"+option3+"</option>";
Update:
for dynamic data from SQL query,
Try putting these codes after query execution. replace $row['value'] and $row['option'] with the respected dynamic values.
echo"<script type='text/javascript'> var str = '' </script>";
while($row = $result->fetch_assoc())
{
echo"<script type='text/javascript'>
str = str + '<option value='+".$row['value']."+'>'+".$row['option']."+'</option>
</script>";
}
echo"<script type='text/javascript'>
document.getElementById('someId').innerHTML = str
</script>";
if you are getting the hospital id then it is very easy to populate the selected value by getting it through from mysql
$query = "SELECT hospital_id, hospital_name FROM mfb_hospital where hospital_id = '$_post['hospital_id']'";
$result = $db->query($query);
$res = mysql_fetch_array($result)
In your select option value code put this code
<option value="your ids here will populate" <?php if($hospital_array['hospital_id']==$res['hospital_id']) echo "selected=selected" ?>>Your hospital name will display here which you selected</option>
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I have the following code to generate my option:
<?php
$sql = "SELECT DISTINCT MyID FROM database";
$query = $db->prepare($sql);
$query->execute();
$option = "";
foreach ($query->fetchAll(PDO::FETCH_ASSOC) as $rows) {
$id = $rows[MyID];
$option.="<option>".$id."</option>";
}
?>
<select name="options" id="options" class="options">
<option value="$id">Select an Option</option>
<?php echo $option?>
</select>
I would like to use the value of the selected option in my next query.. like this:
<?php
$myDB= $db->prepare("SELECT * FROM names WHERE RowID = :option");
$myDB->bindParam(':option', $option); //the value of the option selected in my dropdown
$myDB->execute();
$result = $myDB->fetchAll();
This is not working for some reason. Can you please help on this. Thanks
<?php
$sql = "SELECT DISTINCT MyID FROM database";
$query = $db->prepare($sql);
$query->execute();
$option = "";
$result = $query->fetchAll(PDO::FETCH_ASSOC);
foreach ($result as $row) {
$id = $row['MyID'];
$option.='<option value="'.$id.'">'.$id.'</option>';
}
?>
<form method="post" action"(`The url of the next page`)">
<select name="options" id="options" class="options">
<option disabled>Select an Option</option>
<?php echo $option?>
</select>
<input type="submit" value="submit" />
</form>
Next page:
<?php
if(isset($_POST['submit']) && isset($_POST['options'])) {
$option = $_POST['option'];
$myDB= $db->prepare("SELECT * FROM names WHERE RowID = :option");
$myDB->bindParam(':option', $option); //the value of the option selected in my dropdown
$myDB->execute();
$result = $myDB->fetchAll();
}
With fetchAll() you should assign this to a variable and then loop through that.
$row[MyID] MyID should be wrapped in '' or "" as the index is a string so $row['MyId']
You'll need to submit the data back to the server for PHP to be able to do anything with it as PHP creates he HTML and then sends it from the server to the browser.
I've used if(isset()) for the REQUEST variables ($_GET, $_POST), this will prevent PHP from throwing errors if you try and load the page without them being available.
If you have any other questions, I'd be happy to help.
Hope this helps! :)
EDIT
<?php
if(isset($_GET['submit']) && isset($_GET['options'])) {
$option = $_GET['option'];
$myDB= $db->prepare("SELECT * FROM names WHERE RowID = :option");
$myDB->bindParam(':option', $option); //the value of the option selected in my dropdown
$myDB->execute();
$result = $myDB->fetchAll();
/**
* You'll need to put the logic for the query above here
**/
} else {
$sql = "SELECT DISTINCT MyID FROM database";
$query = $db->prepare($sql);
$query->execute();
$option = "";
$result = $query->fetchAll(PDO::FETCH_ASSOC);
foreach ($result as $row) {
$id = $row['MyID'];
$option.='<option value="'.$id.'">'.$id.'</option>';
}
?>
<form method="get" action"">
<select name="options" id="options" class="options">
<option disabled>Select an Option</option>
<?php echo $option?>
</select>
<input type="submit" value="submit" />
</form>
<?php
} // End of else
?>
I've also changed the form method to get and removed the action, so it will submit to the current page.