Outputting data from database to HTML options and tables - php

I'm new in PHP.
I have a database with 5 columns. "id" "fldName" "fldPrice" "fldSupplier" and "fldPackage".
I have a HTML table with select options where I output "fldName" where "fldPackage" has a spesific value. I have made this work, but I would also like to output the corresponding "fldPrice" from the selected "fldName" when it's chosen. I'm stuck on how to do this.
This is my php:
<?php
function conTroller(){
include("includes/dbh.php");?>
<?php $sql = "SELECT * FROM tbl_price WHERE fldPackage='controller'";
$result = mysqli_query($conn, $sql);
if($result->num_rows> 0){
$options= mysqli_fetch_all($result, MYSQLI_ASSOC);}
foreach ($options as $option) { ?>
<option><?php echo $option['fldName']; ?> </option><?php }}
?>
and this is my HTML
<td><b>Electrical package</b></td>
<td>
<select id="1" class="custom-select" required onchange="ePkg(event)">
<option selected value="">None</option>
<?php conTroller(); ?>
</select>
</td>
<td>I want "fldPrice" to update here when I choose from the options</td>
<td>istL</td>
<td>Select controller</td>
Can anyone help?
I have been reading, googling and looking for similar problems. The biggest problem for me is that I'm not really sure what to search for.

For the simplicity for only updating price when selectbox changed, I suggest to use DOM Manipulation using Javascript
<?php
function conTroller() {
include("includes/dbh.php");
$sql = "SELECT * FROM tbl_price WHERE fldPackage='controller'";
$result = mysqli_query($conn, $sql);
if($result->num_rows> 0){
$options= mysqli_fetch_all($result, MYSQLI_ASSOC);}
foreach ($options as $option) { ?>
<!-- add attribute "data-price" so javascript can get price value from the selected option -->
<option data-price="<?php echo $option['fldPrice']; ?>"><?php echo $option['fldName']; ?> </option><?php
}
}?>
<td><b>Electrical package</b></td>
<td>
<!-- add a function in onchange to update price whenever selectbox changed -->
<select id="1" class="custom-select" required onchange="ePkg(event); updatePrice(this)">
<option selected value="">None</option>
<?php conTroller(); ?>
</select>
</td>
<!-- add attibute "id" so we can access the element to be updated -->
<td id="price-field">I want "fldPrice" to update here when I choose from the options</td>
<td>istL</td>
<td>Select controller</td>
<script>
// function to update price from selected option
function updatePrice(selectbox) {
var price = selectbox.selectedOptions[0].attributes['data-price'].value || '- no price set -';
document.getElementById('price-field').innerHTML = price;
}
</script>
For more advanced flow (eg: getting more product info other than price like description, etc), you will need a separate php file for displaying product info and fetch it using AJAX call. See some tutorial about AJAX and PHP

Steps I did:
PDO is safer.
The first function returns data.
The other is making a presentation.
An additional div with id='fldPrice' will be the place to display the price.
A significant part of the code was done by javascript
function getPackage() {
$db = conn();
$sql = "SELECT id, fldName, fldPrice, fldSupplier, fldPackage FROM tbl_price WHERE fldPackage='controller'";
$sth = $db->prepare($sql);
$sth->execute();
return $sth->fetchAll(PDO::FETCH_ASSOC);
}
function conTroller() {
$options = getPackage();
foreach ($options as $option) {
echo "<option>" . $option['fldName'] . "</option>";
}
}
function ePkg(ev) {
let prices = JSON.parse('<?php echo json_encode(getPackage()); ?>');
let select = document.getElementById('1');
let fldName = select.options[select.selectedIndex].value;
for (let i = 0; i < prices.length; i++) {
if (prices[i]['fldName'] === fldName) {
let d = document.getElementById('fldPrice');
d.innerHTML = 'Prices: ' + prices[i]['fldPrice'];
}
}
}
<td><b>Electrical package</b></td>
<td>
<select id="1" class="custom-select" required onchange="ePkg(event)">
<option selected value="">None</option>
<?php conTroller(); ?>
</select>
</td>
<td>I want "fldPrice" to update here when I choose from the options</td>
<td>List</td>
<td>Select controller</td>
<div id="fldPrice"></div>

Related

Dynamic Dependent Dropdown

I have a form that pulls some dropdown data from an existing db. I've been working on a second dropdown that references the first to get more specific information from a different DB, however it looks like my code is broken somewhere. The first dropdown is populated fine but when i choose a "Manager" the Site dropdown goes blank, I even lose the "Select Site" option.
Any help would be appreciated.
<script src="https://code.jquery.com/jquery-2.1.1.min.js" type="text/javascript"></script>
<script>
function getSite(val) {
$.ajax({
type: "POST",
url:"get_site.php",
data:'manager_id='+val,
success: function(data){
$("#site-list").html(data);
}
});
}
</script>
html/php
Manager<br/>
<select name="manager_id" onChange="getSite(this.value);">
<option value="">Select Manager</option>
<?php
$results = mysql_query("SELECT * FROM _managers");
while ($row_unit = mysql_fetch_array($results)){
?>
<option value="<?php echo $row_unit["id"]; ?>"><?php echo $row_unit["company"]; ?></option>
<?php
}
?>
</select>
<br/><br/>
Site<br/>
<select name="site_id" id="site-list">
<option value="">Select Site</option>
</select>
get_site.php
<?php
include('includes/connect-db.php');
if(!empty($_POST["manager_id"])) {
$manager_id = $_POST["manager_id"];
$results = mysql_query("SELECT * FROM _sites WHERE manager_id = $manager_id");
?>
<option value="">Select Site</option>
<?php
while ($row_site = mysql_fetch_array($results)){
?>
<option value="<?php echo $row_site["id"]; ?>"><?php echo $row_site["site_name"]; ?></option>
<?php
}
}
?>
As per discussion in comment.
I made the adjustment but still not getting my values from the
"get_site.php" file. Although now the "Select Site" stays in the site
dropdown.
Assuming you are getting proper data from MySQL server do some changes in get_site.php as below.
get_site.php
<?
include 'includes/connect-db.php';
if ((!empty($_POST["manager_id"])) && (isset($_POST["manager_id"])))
{
$manager_id = $_POST["manager_id"];
$results = mysql_query("SELECT * FROM _sites WHERE manager_id = '{$manager_id}'");
$options = "<option value=''>Select Site</option>";
while ($row_site = mysql_fetch_assoc($results))
{
$options .= "<option value='{$row_site['id']}''>{$row_site['site_name']}</option>";
}
return $options; // I personally prefer to echo using json_encode and decode it in jQuery
}
?>
Above code should give you the data you want.
Hope this solves your issue.Do comment if you are having any difficulties.

Updating MySql DB with Dropdown values

My update statement isn't working correctly, I am attempting to pull the data from the database, populate a dropdown with either "Y" or "N" inside it, on submit the values are entered into the database and the page refreshes.
So far I have my list of items, each with correctly populated dropdown, it is now my submit that is failing to work.
<?php
$updatedFeatProd = $_POST['featuredProduct'];
var_dump($updatedFeatProd);
if ($_POST) {
foreach ($_POST['featuredProduct'] as $key => $val) {
$query = 'UPDATE tblProducts SET featuredProduct = ' . $updatedFeatProd . '
WHERE fldID = ' . $val;
$sql = dbQuery($query);
}
}
$sql = dbQuery('SELECT fldId, fldName, featuredProduct FROM tblProducts');
?>
<form method="post" action="#" name="featuredProd">
<table>
<tr><td><p>Product Name</p></td><td><p>Is a featured product?</p></td></tr>
<?php
$products = dbFetchAll($sql);
foreach ($products as $product) {
//var_dump($product['fldName']);
?>
<tr>
<td>
<p><?php echo $product['fldName']; ?></p>
</td>
<td>
<select name="featuredDropdown">;
<?php
if ($product['featuredProduct'] == 'Y') {
?>
<option value="<?php $product['fldId'] ?>"><?php echo $product['featuredProduct'] ?></option>
<option value="<?php $product['fldId'] ?>">N</option>
<?php
} else {
?>
<option value="<?php $product['fldId'] ?>"><?php echo $product['featuredProduct'] ?></option>
<option value="<?php $product['fldId'] ?>">Y</option>
<?php
}
?>
</select>
</td>
</tr>
<?php
}
?>
The presentaton here does not make much sence. You have a dropdown with the ProductName in one slot and a 'N' in another.
Once the user has selected 'N' for a product they have no idea what they have said NO to, as they can no longer see the product name that they have selected NO for.
It would make more sence to provide a <label> containing the product name and a YES/NO dropdown beside it for them to select from.
However the reason your update code is not working is that you have called the dropdown featuredDropdown
<Select name="featuredDropdown">
and you are trying to process a field called featuredProduct in the update code
foreach ($_POST['featuredProduct'] as $key => $val) {
Your next problem will probably be that you are oututting more than one <Select name="featuredDropdown"> so you need to make that into an array as well like this:
<Select name="featuredDropdown[]">
Then you will have an array of featuredDropdown in the $_POST array. $_POST['featuredDropdown'][]

Dynamic drop down list to fill in a text box

I have searched high and low for a resolution to this bus have not been able to work it out. I managed to get this to work when I wanted a dynamic drop down to adjust the values in a second drop down and fill in a text value in a text box.
Now I want to cut out the second step: ie. I actually want to get rid of the second drop down and simply enter a value in the text box. I have tried everything to remove the second step but as soon as I do everything stops working.
At the moment the function looks at the second drop down and sets the options for it and I added the line
document.getElementById('fld_ClientID').value =""
to get it to enter the data in the text box. How do I get rid of the reference to the tblPromotions completely and make it get the data for the text box only.
<script language="javascript">
function setOptions(chosen) {
var selbox = document.myform.selectpromotion;
selbox.options.length = 0;
if (chosen == "0") {
selbox.options[selbox.options.length] = new Option('First select a client','0');
}
<?php
$client_result = mysql_query("SELECT * FROM tblClients ORDER BY ClientName") or die(mysql_error());
while(#($c=mysql_fetch_array($client_result)))
{
?>
if (chosen == "<?=$c['ClientID'];?>") {
<?php
$c_id = $c['ClientID'];
$promo_result = mysql_query("SELECT * FROM tblPromotions WHERE ClientID='$c_id'") or die(mysql_error());
while(#($m=mysql_fetch_array($promo_result)))
{
?>
selbox.options[selbox.options.length] = new
Option('<?=$m['PromotionName'];?>','<?=$m['ClientID'];?>');
document.getElementById('fld_ClientID').value ="<?=$m['ClientID'];?>";
<?php
}
?>
}
<?php
}
?>
}
</script>
</head>
<body>
<form name="myform" method="POST" action="processaddpromotionNEW.php"> ><div align="center">
<p>
<select name="selectclient" size="1"
onchange="setOptions(document.myform.selectclient.options
[document.myform.selectclient.selectedIndex].value);">
<option value="0" selected>Select a client</option>
<?php
$result = mysql_query("SELECT * FROM tblClients ORDER BY ClientName") or die(mysql_error());
while(#($r=mysql_fetch_array($result)))
{
?>
<option value="<?=$r['ClientID'];?>">
<?=$r['ClientName'];?>
</option>
<?php
}
?>
</select>
<br><br>
<select name="selectpromotion" size="1">
<option value=" " selected>First select a client</option>
</select>
</p>
<p>
<input name="fld_ClientID" type="text" class="Arial" id="fld_ClientID" tabindex="11" size="10" />
<br>
maybe, you shouldn't do a mysql query inside a javascript function. you should either:
use ajax to get the possible options
or
query all the possible options once then save it on a global variable
something like:
<script>
var secondOptions = {};
<?php
$promo_result = mysql_query("SELECT * FROM tblPromotions") or die(mysql_error());
while(#($m=mysql_fetch_array($promo_result))){
?>
if(secondOptions['<?=$m['ClientID'];?>'] == undefined)
secondOptions['<?=$m['ClientID'];?>'] = {};
secondOptions['<?=$m['ClientID'];?>']['<?=$m['PromotionId'];?>'] = '<?=$m['PromotionName'];?>';
<?php
}
?>
setOptions(clientId){
jQuery("select[name=selectpromotion]").empty();
options = "";
jQuery.each(secondOptions[clientID],function(a,b){
options += "<option value='"+a+"'>"+b+"</options>";
});
jQuery("select[name=selectpromotion]").append(options);
}
<select name="selectclient" size="1" onchange="setOptions(jQuery(this).val());">
...

related dropdown list

I'm new in PHP.. I need your help..
I have 2 dropdownlist that related:
dropdown 1 : manually insert the value
dropdown 2 : attach value from database (value based on condition that selected in dropdown 1)
Then, both value which are selected will display in textbox at another form.
My problem is:
1) The value in 2nd dropdown can't be display.
2) The value in 1st dropdown can pass to other form but the 2nd can't.
Please kindly guide me.
I don't know how to share my code here.
form1.php
//1st dropdown
<select name="fruit_name" id="fruit_name" style="font-family: Calibri;font-size: 10pt;" onchange="loadXMLDoc(this.value); ">
<option value="0">-- please choose --</option>
<option value="Pineapple">Pineapple</option>
<option value="Apple">Apple</option>
//2nd dropdown
$fruit_name = $_POST['fruit_name'];
#Connect to MySQL
#Connect to database
$result = mysql_query("SELECT colour FROM fruit WHERE fruit_name = '$fruit_name'");
echo "<select name='colour' id='colour' style='font-family: Calibri;font-size: 10pt;'>";
while($row = mysql_fetch_assoc($result))
{
echo "<option value = ''>" . $row['colour'] . "</option>";
}
echo "</select>";
mysql_free_result($result);
//Closes specified connection
?>
form2.php
<?php
//connection
$fruit_name = $_POST['fruit_name'];
$colour = $_POST['colour'];
?>
<label>
<input type="text" name="fruit_name" id="fruit_name" value = "<?php echo $fruit_name;?>" readonly>
</label>
<p>
<label>
<input type="text" name="colour" id="colour" value="<?php echo $colour;?>" readonly>
</label>
</p>
I usually don't do this but since I've some spare time on hand right now, I'm going to give the general approach that you can follow:
Include the following between your <head> tag.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
Below that, paste this code
<script type="text/javascript">
$(function(){
$('select#fruit_name').change(function(){
var selectedVal = $(this).val(); // get the selected value
$.ajax({ // send ajax request to the php file to process data
type:'post',
url:'php-page-name.php',
data:{'value':selectedVal},
success:function(ret) // display the result from php-page-name.php page
{
$('div#result').html(ret);
}
});
});
});
</script>
Lets move on to your HTML now
<select name="fruit_name" id="fruit_name" style="font-family: Calibri;font-size: 10pt;">
<option value="0">-- please choose --</option>
<option value="Pineapple">Pineapple</option>
<option value="Apple">Apple</option>
</select>
<div id="result">
<select>
<option>Select One</option>
</select>
</div>
php-page-name.php page (Do not forget to create this page and put it in the same folder as form1.php)
<?php
// put the code to connect to your database here
$fruit_name = $_POST['value']; // this will contain the value selected from first dropdown
$result = mysql_query("SELECT colour FROM fruit WHERE fruit_name = '$fruit_name'");
echo "<select name='colour' id='colour' style='font-family: Calibri;font-size: 10pt;'>";
while($row = mysql_fetch_assoc($result))
{
echo "<option value = '".$row['colour']."'>" . $row['colour'] . "</option>";
}
echo "</select>";
mysql_free_result($result);
?>
PS : I'm using the mysql_* functions in this example since I'm assuming you're too. But this is not recommended as they are going to be deprecated soon. You might want to switch to mysqli or PDO

PHP: Echo value of selected item from a dependable dropdown menu

I am currently working with a Dependable dropdown menu that functions with the help of jQuery and PHP. The values are being pulled of MySQL database. Is there away to php echo the selected value of a dependable drop down menu?
EXAMPLE
HTML/PHP
<form action="" method="post">
<select name="gender" id="gender" class="update">
<option value="">Select one</option>
<?php if (!empty($list)) { ?>
<?php foreach($list as $row) { ?>
<option value="<?php echo $row['id']; ?>">
<?php echo $row['name']; ?>
</option>
<?php } ?>
<?php } ?>
</select>
<select name="category" id="category" class="update"
disabled="disabled">
<option value="">----</option>
</select>
<select name="colour" id="colour" class="update"
disabled="disabled">
<option value="">----</option>
</select>
</form>
Please add jquery.js.
your html code
<select name="gender" id="gender" class="update">
<option value="">Select one</option>
<?php if (!empty($list)) { ?>
<?php foreach($list as $row) { ?>
<option value="<?php echo $row['id']; ?>">
<?php echo $row['name']; ?>
</option>
<?php } ?>
<?php } ?>
</select>
<select name="category" id="category" class="update" disabled="disabled">
<option value="">----</option>
</select>
<select name="colour" id="colour" class="update" disabled="disabled">
<option value="">----</option>
</select>
//jquery code for source list
<script type="text/javascript">
$(document).ready(function(){
$('#gender').change(function() {
if ($(this).val()!='') {
$("#category").load("postfile.php",{gender_id: $(this).val()});
$("#category").removeAttr('disabled');
}
});
//code on change of sel_source
$('#category').change(function() {
if ($(this).val()!='') {
$("#colour").load("postfile.php",{category_id: $(this).val()});
$("#colour").removeAttr('disabled');
}
});
});
</script>
//postfile.php
//your mysql connection other things goes here
//code for category
$objDb = new PDO('mysql:host=localhost;dbname=dbname', 'ur_username', 'ur_password');
if(isset($_REQUEST['gender_id']) && !empty($_REQUEST['gender_id'])) {
$sql = "SELECT * FROM `categories` WHERE `master` = ?";
$statement = $objDb->prepare($sql);
$statement->execute(array($_REQUEST['gender_id']));
$list = $statement->fetchAll(PDO::FETCH_ASSOC);
if(!empty($list)) {
$output = '<option value="">Select</option>';
foreach($list as $row) {
$output .= '<option value="'.$row['id'].'">'.$row['name'].'</option>';
}
} else {
$output = '<option value="">Select</option>';
}
echo $output;
}
//code for color
if(isset($_REQUEST['category_id']) && !empty($_REQUEST['category_id'])) {
$sql = "SELECT * FROM `categories` WHERE `master` = ?";
$statement = $objDb->prepare($sql);
$statement->execute(array($_REQUEST['category_id']));
$list = $statement->fetchAll(PDO::FETCH_ASSOC);
if(!empty($list)) {
$output = '<option value="">Select</option>';
foreach($list as $row) {
$output .= '<option value="'.$row['id'].'">'.$row['name'].'</option>';
}
} else {
$output = '<option value="">Select</option>';
}
echo $output;
}
Hope this will help you.
You are going to have to write a JavaScript function that retrieves the selected value or option from the first HTML select field. This function commonly writes out a new URL path to the current page with the addition of some concatonated Get Variables:
<script type="text/javascript">
getSelectedOptionValue() {
// create some variables to store your know values such as URL path and document
var myPath = " put the URL path to the current document here ";
var currentPage = "currentPage.php";
// get the values of any necessary select fields
var carMake = document.getElementById("carMake").value;
// write out the final URL with the Get Method variables you want using concatnitation
var getMethodURL = myPath + currentPage + "?carMake='" + carMake + "'";
// function refreshes page using the function made URL
window.location.replace( getMethodURL );
}
</script>
Since the second select field is dependent on the first you have to assume that the user is going to make a selection from the first choice of options. This means that the function that retrieves the value of the primary select field must run in response to a change in the fields selection. For example
<select name="carMake" id="carMake" onchange="getSelectedOptionValue();">
Depending on how you have set up your DB, you may want either the value of the option tag or the string presented to the user between the option tags...this is up to you keeping in mind how you may re-query the information if your original record set hasn't already pulled up the necessary info to write the second set of select option tags.
To write out the second select field using php simply repeat the while loop you have used for the first. This time replace your SQL statement with a new one using a variable in which you have stored the value retrieved from the new URL using the get method
<?php
// here I am using the more generic request method although you could use the get as well
$carMake = $_REQUEST['carMake'];
sql_secondSelectField = "SELECT * FROM tbl_carModels WHERE carMake = $carMake";
// Run new query and repeat similar while loop used to write your first select field ?>

Categories