首页 > 解决方案 > 如何从 html/php 表单添加到 HTML 表格?

问题描述

我想创建一个包含 2 个字段和 2 个按钮的表单。字段 1:名称和字段 2:地址 按钮 1:提交和按钮 2:删除

我想从表单添加到字段 1
我想从表单添加到字段 2

    <td>field 1</td>
<td class='latency' id='field 1' endpoint='field 2'>&nbsp;</td>

代码写的是js,htl代码是这样的

     <td>US-East)</td>
    <td class='latency' id='us-east-1' endpoint='https://amazon.com/'>&nbsp;</td>

我如何编写一个 php/html 表单来做到这一点?或者我在哪里可以获得有关如何执行此操作的信息?

标签: phphtml

解决方案


安全注意事项:使用来自最终用户的数据输入时,应始终清理用户条目。为此目的,有内置的 php 函数。我没有在我的回答中详细介绍这一点,我只是向您展示如何实现您要求实现的有关 FORM 创建和显示来自所述表单的动态值的功能。

HTML 特殊字符:https ://www.php.net/manual/en/function.htmlspecialchars.php

您的起点将是 html,使用 POST 方法创建一个表单。 <form action="formpage.php" method="post"></form><--formpage.php应该是您希望将数据发送到以进行处理的 php 页面。

action属性将引用您希望表单将输入结果发布到的页面--->$_POST['input-name']

method属性指定如何发送 form-data(form-data 发送到 action 属性中指定的页面)。表单数据可以作为 URL 变量(使用 method="get")或作为 HTTP post 事务(使用 method="post")发送。

典型的形式如下所示。

<form action="mypage.php" method="post"> 
    <input type="text" name="name" placeholder="Enter a Name" required>
    <input type="text" name="address" placeholder="" required>
    <input type="reset" value="Reset"><!--// Will reset the form to their original form values-->
    <input type="submit" name="submit" value="Submit Form">    
</form>

现在,一旦用户点击提交按钮,就会通过 HTTP 发布请求发送三个值。这些在输入字段中被引用为name属性。

  1. 姓名
  2. 地址
  3. 提交

在 mypage.php 上,我们现在可以使用发布的全局变量引用从用户输入发送的值。

$_POST['name'] =    // the input field that has the name attribute set to `"name"`

$_POST['address'] = // the input field that has the name attribute set to `"address"`

$_POST['submit'] =  // the input field that has the name attribute set to `"submit"`

编辑:动态创建以创建表格并显示表单结果

$table = NULL;
if(isset($_POST['submit'])){ // check to see if the submit button was hit and isset
    // assign the post values to variables
    $name = htmlspecialchars($_POST['name']); 
    $address = htmlspecialchars($_POST['address']);

    // if you want to create the table dynamically now.
    $table .= '
              <table>
                  <tr>';
    if($name!==NULL){
        $table .= '
        <td>Name: '.$name.'</td>';
    }
    if($address!==NULL){
        $table .= '
        <td>address: '.$address.'</td>';
    }
    $table .= '
                  </tr>
              <table>';
}

要将表格放置在您的代码中,只需在您希望表格所在的位置回显$table变量即可。HTML

<?=$table?>

结束编辑

定义所用变量的 php 代码需要在<html>标签上方的页面顶部声明。

我们也可以在同一页面上的 HTML 代码中引用这些变量。 <?=是相同的<?php echo

<td class='latency' id='<?=$name?>' endpoint='<?=$address?>'>&nbsp;</td>    

希望这可以帮助您入门。


推荐阅读