从表单按钮调用PHP函数

时间:2019-02-27 20:06:25

标签: php html forms function button

enter image description here

我的脚本应该看起来像这样。我必须主要在PHP中进行操作。 Button添加应将数据保存到文件,节目应读取该文件并将其放入textarea,删除必须删除选择的行,然后重置将重置所有内容。

<?php
    $plik =fopen("data.dat","a+");
    @fputs($plik, $_POST["name"]. " " . $_POST["sname"] . " " . $_POST["adres"] . " " . $_POST["number"] . "<br>" );    
    fclose($plik);  
?>

<html>

   <body>

   <form action = "<?php $_PHP_SELF ?>" method = "POST">

         Name: <input type = "text" name = "name" /><br>
         Second Name: <input type = "text" name = "sname" /><br>
         Adres: <input type = "text" name = "adres" /><br>
         Number: <input type = "text" name = "number" /><br>
         <input type = "submit" name="add" value="Add"/>
         <input type = "button" name="show" value="Show"/>
         <input type = "button" name="reset" value="Reset"/>
         <input type = "button" name="delete" value="Delete"/><br>
         <textarea id="lista" name="lista" rows="20" cols="40" style="overflow:scroll" readonly="" wrap="off"></textarea>

      </form>

   </body>

</html>

我的脚本看起来像这样,我不知道下一步该怎么做。如何向这些按钮添加功能,以及它们的外观如何?

1 个答案:

答案 0 :(得分:2)

我认为这应该可以完成工作:

<?php
    if(isset($_POST['action'])) {
       switch($_POST['action']) {
         case('Add'): ... break;
         case('Show'): ... break;
         case('Reset'): ... break;
         case('Delete'): ... break;
         default: ...
       }
    }
    ?>

    <html>
       <body>

       <form action = "<?php $_PHP_SELF ?>" method = "POST">
             Name: <input type = "text" name = "name" /><br>
             Second Name: <input type = "text" name = "sname" /><br>
             Adres: <input type = "text" name = "adres" /><br>
             Number: <input type = "text" name = "number" /><br>
             <input type = "submit" name="action" value="Add"/>
             <input type = "submit" name="action" value="Show"/>
             <input type = "submit" name="action" value="Reset"/>
             <input type = "submit" name="action" value="Delete"/><br>
             <textarea id="lista" name="lista" rows="20" cols="40" style="overflow:scroll" readonly="" wrap="off"></textarea>
          </form>

       </body>
    </html>

如您所见,我刚刚将操作按钮的类型更改为“提交”,并为所有按钮设置了相同的名称。然后在php中,只需测试是否设置了动作,然后选择要执行的正确动作即可。希望对您有帮助