-2

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>
Adii
  • 5
  • 3
  • This code works perfectly well, as far as it goes. What's the actual problem? –  Dec 16 '20 at 00:50
  • If you're going to use CSV as opposed to DBs you should use the proper functions https://www.php.net/manual/en/function.fgetcsv.php. Not really clear what you mean by `only PHP`. (DB would/will be easier and function better) – user3783243 Dec 16 '20 at 02:07

1 Answers1

0

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

Lawrence Cherone
  • 46,049
  • 7
  • 62
  • 106