使用动态字段将数据插入数据库

时间:2018-11-11 18:24:44

标签: javascript php jquery html database

我正在使用动态文本框。

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

我的标记:

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

3 个答案:

答案 0 :(得分:0)

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

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

将表单元素名称更改为

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
}

就是这样! 就像我说的那样,这不一定是实现目标的最佳方法,但到目前为止,这是最简单的

答案 1 :(得分:0)

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

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

CalendarApp.getDefaultCalendar()

答案 2 :(得分:-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();
}