Home > OS >  Outputting data from database to HTML options and tables
Outputting data from database to HTML options and tables

Time:12-13

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"  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.

CodePudding user response:

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"  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

  • Related