【问题标题】:Inserting data to the database with dynamic fields使用动态字段将数据插入数据库
【发布时间】:2019-04-14 13:31:45
【问题描述】:

我正在使用动态文本框。

我想将在文本框中输入的数据添加到我的数据库中。

我的标记:

<form name="reaction" id="reaction" method="post" action="./send.php">
    <input type="text" name="number[]" id="number1" value="15" placeholder="Number 1" /> <br />
    <input type="text" name="name[]" id="name1" value="aaaa" placeholder="Name 1" /> <br />
    <input type="text" name="price[]" id="price1" value="10" placeholder="Price 1" /> <br />
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <script>
        $(document).on('click', '#add_row', function(){
            count++;
            $('#total_item').val(count);
            var html_code = '';
            html_code += '<input type="text" placeholder="Number '+count+'" name="number[]" id="number'+count+'" data-srno="'+count+'" /><br />';
            html_code += '<input type="text" placeholder="Name '+count+'" name="name[]" id="name'+count+'" data-srno="'+count+'" /><br />';
            html_code += '<input type="text" placeholder="Price '+count+'" name="price[]" id="price'+count+'" data-srno="'+count+'" /><br />';
            html_code += '<button type="button" name="remove_row" id="'+count+'" class="btn btn-danger btn-xs remove_row">X</button><br />';
        });
    </script>
    <button type="submit" class="btn btn-primary" name="send">Save</button>
</form>

这会产生以下文档片段:

<form name="reaction" id="reaction" method="post" action="./send.php">
    <input type="text" name="number[]" id="number1" value="15" placeholder="Number 1" /> <br />
    <input type="text" name="name[]" id="name1" value="aaaa" placeholder="Name 1" /> <br />
    <input type="text" name="price[]" id="price1" value="10" placeholder="Price 1" /> <br />
    <input type="text" name="number[]" id="number2" value="12" placeholder="Number 2" /> <br />
    <input type="text" name="name[]" id="name2" value="bbbb" placeholder="Name 2" /> <br />
    <input type="text" name="price[]" id="price2" value="15" placeholder="Price 2" /> <br />
    <input type="text" name="number[]" id="number3" value="38" placeholder="Number 3" /> <br />
    <input type="text" name="name[]" id="name3" value="cccc" placeholder="Name 3" /> <br />
    <input type="text" name="price[]" id="price3" value="29" placeholder="Price 3" /> <br />
    <button type="submit" class="btn btn-primary" name="send">Save</button>
</form>

在提交表单时,我想将以下数据添加到数据库中:

| session_id  |  number  |   name   |   price  |
|-------------|----------|----------|----------|
|      1      |    15    |   aaaa   |    10    |
|      1      |    12    |   bbbb   |    15    |
|      1      |    38    |   cccc   |    29    |

在我的 PHP 代码中,我使用以下代码来定义文本框:

foreach($_POST['number'] as $i => $item) {

当我执行脚本时,我只得到前三个文本框的数据。我进入我的数据库:

| session_id  |  number  |   name   |   price  |
|-------------|----------|----------|----------|
|      1      |    15    |   aaaa   |    10    |

经过数周的研究,我发现代码的 JavaScript 部分有问题。当我在第二个示例中使用文本框发送数据时,我得到了我想要的结果。当我使用 JavaScript 创建动态文本框时,PHP 脚本只会将第一行(不是使用 JavaScript 创建的)发布到数据库中。

我的脚本有什么问题?

这是我用来向数据库添加数据的脚本:

<?php
    $correct = true;
    $_SESSION['session_id'];
    $number = $_POST['number'] ;
    $name = $_POST['name'] ;
    $price = $_POST['price'] ;
    if($correct){
        foreach($_POST['number'] as $i => $item) {
            $db = new PDO('mysql:host=localhost;dbname=db', 'user', 'pass');
            $query= "INSERT INTO products(session_id, number, name, price) VALUES (:session_id, :number, :name, :price)";
            $stmt = $db->prepare($query);
            $exec = $stmt->execute(array(
                ':session_id' => $_SESSION['session_id'],
                ':number' => $_POST["number"][$i],
                ':name' => $_POST["name"][$i],
                ':price' => $_POST["price"][$i]
            ));
        }
    }
    else
    {
        header('Location: ../error.php');
    }
?>

var_dump$_POST['number'] 上的结果:

array(1) { [0]=> string(2) "15" }

【问题讨论】:

  • 您的意思是让价格字段具有name="name[]
  • 你能在foreach循环之前分享$_POST['number']的dump_var吗?
  • 我已经修改了脚本。
  • 当我在 $_POST['number'] 上执行 var_dump 时,我得到:array(1) { [0]=> string(2) "15" }
  • var_dump 的输出肯定看起来不正确。你有多少个&lt;form&gt; 标签?这只是正常提交​​,即不是通过 AJAX 提交吗?

标签: javascript php jquery html database


【解决方案1】:

不要注入纯 html,而是使用 DOM。

<form name="reaction" id="reaction" method="post" action="./send.php">
    <button type="submit" class="btn btn-primary" name="send">Save</button><br />
</form>

<script>
function newInput(type, value, count){
    var newInput = document.createElement('input');
    newInput.type = 'text';
    newInput.name = type+'[]';
    newInput.id = type+count;
    newInput.value = value;
    newInput.placeholder = type+' '+count; // <--you probably want to camelize this
    return newInput;
}

function addRow(number, name, price, count, target){
    target.appendChild(newInput('number', number, count));
    target.appendChild(newInput('name', name, count));
    target.appendChild(newInput('price', price, count));
    target.appendChild(document.createElement('br')); // <-- create any element
}

var myForm = document.getElementById('reaction');
var count = 0;
addRow(111, 'one', 1, ++count, myForm);
addRow(222, 'two', 2, ++count, myForm);
addRow(333, 'three', 3, ++count, myForm);
addRow(444, 'four', 4, ++count, myForm);
</script>

PHP 部分看起来几乎没问题:

$post_number = $_POST['number'];
$post_name = $_POST['name'];
$post_price = $_POST['price'];

//check, if needed set session variables here, then
$ses_id = session_id();

$db = new PDO('mysql:host=localhost;dbname=test', 'root', '');
$query= "INSERT INTO products(session_id, number, name, price) VALUES (:session_id, :number, :name, :price)";

foreach($_POST['number'] as $i => $item) {
    $stmt = $db->prepare($query);
    $exec = $stmt->execute(array(
        ':session_id' => $ses_id,
        ':number' => $post_number[$i],
        ':name' => $post_name[$i],
        ':price' => $post_price[$i]
    ));
    if($exec == false)
        header('Location: ../error.php');
        //or print out what happened
        //$e = $stmt->errorInfo();
        //print_r($e);
        //die();
}

【讨论】:

    【解决方案2】:

    您可以使用数组名称保留表单字段,但为了将数据发布到数据库,您需要遍历数组。

    因此,您的接收页面应该将所有表单数据收集到 $_POST 变量中,然后您可以将发布的值解析为 $_POST['number'] 并使用 for-each 循环遍历数组。

    foreach ($_POST['price'] as $key => $value) {
         // do something with array value
        echo "{$key} => {$value} ";
    
        print_r($_POST['price']);
    }
    

    【讨论】:

      【解决方案3】:

      主要问题是表单中的所有字段都具有相同的名称,即使它们应该是数组,但实际上并不允许多行。

      最简单(不一定是最佳)的方法是进行一些调整

      将表单元素名称更改为

      variable[$i][number]
      variable[$i][name]
      variable[$i][price]
      

      并确保您的表单更改每一行上$i 的值,以便您的表单变为:

      <form name="reaction" id="reaction" method="post" action="./send.php">
      <input type="text" name="variable[0][number]" id="number1" value="15" placeholder="Number 1" /> <br />
      <input type="text" name="variable[0][name]" id="name1" value="aaaa" placeholder="Name 1" /> <br />
      <input type="text" name="variable[0][price]" id="price1" value="10" placeholder="Price 1" /> <br />
      
      <input type="text" name="variable[1][number]" id="number1" value="15" placeholder="Number 1" /> <br />
          <input type="text" name="variable[1][name]" id="name1" value="aaaa" placeholder="Name 1" /> <br />
          <input type="text" name="variable[1][price]" id="price1" value="10" placeholder="Price 1" /> <br />
      

      等等…… 然后,更改您的表单处理以迭代 $variable

      foreach($variable as $var)
      {
         $number = $var['number'];
         $name = $var['name'];
         $price = $var['price'];
      
         // do whatever it is you do with the variables and then loop to the next row
      }
      

      就是这样! 就像我说的,这不一定是实现目标的最佳方式,但它是迄今为止最简单的

      【讨论】:

      • 您确定name="variable[0][number]" 可以与$var['number']; 一起使用吗?当我运行脚本 (send.php) 时,我收到 HTTP ERROR 500 错误,因为变量不正确
      • 我发现我的代码中的 Javascript 部分有问题。所以我更新了我的问题。可以看看吗?
      • 是的,以上是正确的。这正是我的做法......虽然我没有提供完整的代码,因为它是一个指导,如果你只是复制粘贴上面的内容,这可能是你得到 500 错误的原因。您需要将$_POST['variable'] 读入一个变量,然后再对其进行迭代。
      猜你喜欢
      • 2015-06-21
      • 2020-07-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-03
      • 2021-01-26
      相关资源
      最近更新 更多