【问题标题】:Is it possible with only PHP ? PHP FORM只有 PHP 有可能吗? PHP 表单
【发布时间】:2021-03-26 15:26:22
【问题描述】:

我有一个 .csv 文件,其中包含产品名称及其数量,以逗号分隔。 我想从 ComboBox 中选择一个产品,并将其数量显示为我输入的数字类型的“最大值” . 这是 .csv 文件的示例:

   Xbox,12
   Playstation,15
   Switch,13

这是我的 HTML 和 PHP 代码示例:

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

【问题讨论】:

  • 这段代码运行良好,就目前而言。真正的问题是什么?
  • 如果你打算使用 CSV 而不是 DB,你应该使用正确的函数 php.net/manual/en/function.fgetcsv.php。不太清楚only PHP 是什么意思。 (DB 会/将会更容易并且功能更好)

标签: php forms csv dynamic


【解决方案1】:

不,因为 PHP 只是服务器端。阅读What is the difference between client-side and server-side programming?

但是将它放入 json 并在 select 上使用 onchange 事件然后从对象中获取值然后设置到数量字段中是微不足道的。

注意,你真的应该在输出之前先做 PHP 东西,以防出现任何错误,因为我们将多次重用 $products

例子:

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

工作示例:https://repl.it/@lcherone/BlueCreepyApplicationstack#index.php

【讨论】:

    猜你喜欢
    • 2011-03-19
    • 1970-01-01
    • 2012-08-28
    • 1970-01-01
    • 2011-02-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多