Skip to content
Advertisement

Is it possible with only PHP ? PHP FORM

I have a .csv file which contains the name of a product and its quantity separated by a comma. I would like to choose a product from the ComboBox and have its quantity displayed into ‘max’ of my input of numer type . Here is a sample of the .csv file :

   Xbox,12
   Playstation,15
   Switch,13

Here is a sample of my HTML and PHP code :

<form class="" method="POST" action="index.php">
        <label for="product"> Produit </label>
        <select name="product" id="espace">
        <option value="">--Please choose a product--</option>
        <?php
             $file = fopen('prodct.csv', 'r');
              if ($file){
                while ($ligne = fgets($file))
                  {
                      $l = explode(',', $ligne);
                      echo '<option value="'.$l[0].'">'.$l[0].'</option>';
                  }
                  
                  fclose($file);
              }
        ?>
       </select>
       <br> <label for="quantity"> Quantity </label>
       <input type="number" name="quantity" value="" min="0" max=""/>
</form>

Advertisement

Answer

No, because PHP is serverside only.. Have a read of What is the difference between client-side and server-side programming?

But is trivial to put it into json and use an onchange event on the select to then get the value from an object and then set into the quantity field.

Note, you should really always do PHP stuff first before output incase of any errors and because we are going to reuse $products more than once.

Example:

<?php
$products = [];
$file = fopen('prodct.csv', 'r');
if ($file) {
  while ($ligne = fgets($file)) {
    $l = explode(',', $ligne);
    $products[trim($l[0])] = trim($l[1]);
  }
  fclose($file);
}
?>

<form class="" method="POST" action="index.php">
  <label for="product"> Produit </label>
  <select name="product" id="espace">
    <option value="">--Please choose a product--</option>
    <?php foreach(array_keys($products) as $product):?>
    <option><?= $product ?></option>
    <?php endforeach; ?>
  </select>
  <br> <label for="quantity"> Quantity </label>
  <input type="number" name="quantity" value="" min="0" max="" />
</form>

<script>
let products = <?= json_encode($products) ?>

document.querySelector('[name="product"]').addEventListener("change", function() {
  document.querySelector('[name="quantity"]').value = products[this.value]
});
</script>

Working example: https://repl.it/@lcherone/BlueCreepyApplicationstack#index.php

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement