在表单中创建输入组并通过 PHP 中的 POST 访问它们

Gio*_*gio 3 html php mysql

是否可以$_POST使用 PHP 以关联数组的方式创建输入组并访问它们?我有一个表单,用户可以在其中输入有关产品的信息。每个产品都有一个名称和一个描述。

简单的解决方案

在典型的形式中,我会创建一个 HTML 结构,如:

<form method="post" id="insert" action="test.php">
  <!-- First product -->
  <input type="text" name="title1"/>
  <input type="text" name="description1"/>

  <!-- Second product -->
  <input type="text" name="title2"/>
  <input type="text" name="description2"/>

  <input type="submit" name="submit" value="Insert products" />
</form>
Run Code Online (Sandbox Code Playgroud)

并通过 PHP 访问数据:

if(isset($_POST['submit']))
{
  echo 'Submitted data:<br/>';
  echo 'title='.$_POST['title1'].' description='.$_POST['description1'].'<br/>';
  echo 'title='.$_POST['title2'].' description='.$_POST['description2'].'<br/>';
}
Run Code Online (Sandbox Code Playgroud)


棘手(但更难)的伪解决方案

我想创建的是一个 HTML 伪代码,其中产品输入按结构分组,带有标题和描述,如下所示:

<form method="post" id="insert" action="test.php">
  <!-- First product -->
  <div name="products[]">
    <input type="text" name="title"/>
    <input type="text" name="description"/>
  </div>

  <!-- Second product -->
  <div name="products[]">
    <input type="text" name="title"/>
    <input type="text" name="description"/>
  </div>

  <input type="submit" name="submit" value="Insert products" />
</form>
Run Code Online (Sandbox Code Playgroud)

用于访问输入的 PHP 伪代码:

if(isset($_POST['submit']))
{
  echo 'Submitted data:<br/>';

  foreach($_POST["products"] as $product)
  {
    echo 'title='.$product['title'].' description='.$product['description'].'<br/>';
  }
}
Run Code Online (Sandbox Code Playgroud)

可行吗?提前致谢。

Kev*_*vin 5

是的,您可以为该属性使用分组名称,以便在提交时对其进行分组。该name=""div 中的组不正确,它必须在输入元素上。例子:

<?php

if(isset($_POST['submit'])) {
    $products = $_POST['products']; // assuming they are all filled, they will be here inside
    echo '<pre>';
    print_r($products); // check the results
}


?>

<form method="post" id="insert" action="">
  <!-- First product -->
  <!-- group them by row index -->
  Title: <input type="text" name="products[1][title]"/>
  Description: <input type="text" name="products[1][description]"/>
  <br/><br/>
  <!-- Second product -->
  Title: <input type="text" name="products[2][title]"/>
  Description: <input type="text" name="products[2][description]"/>
  <br/><br/>
  <input type="submit" name="submit" value="Insert products" />
</form>
Run Code Online (Sandbox Code Playgroud)

超级基本的插入示例(这只是一个例子,你可以使用也可以不使用):

if(isset($_POST['submit'])) {
    $products = $_POST['products'];

    $db = new mysqli('localhost', 'username', 'password', 'database');
    $insert = $db->prepare('INSERT INTO `table_name` (`title`, `description`) VALUES (?, ?)');
    foreach($products as $product) {
        $insert->bind_param('ss', $product['title'], $product['description']);
        $insert->execute();
    }
    $insert->close();
}
Run Code Online (Sandbox Code Playgroud)