简体   繁体   English

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

[英]Inserting data to the database with dynamic fields

I am working with dynamic text boxes. 我正在使用动态文本框。

I want to add the data that is entered in the text boxes to my database. 我想将文本框中输入的数据添加到我的数据库中。

My markup: 我的加价:

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

Which results in the following document fragment: 这导致以下文档片段:

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

When submitting the form I want to add the following data to the database: 提交表单时,我想将以下数据添加到数据库:

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

In my PHP code I am using the following to define the text boxes: 在我的PHP代码中,我使用以下内容来定义文本框:

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

When I execute the script I only get the data of the first three textboxes. 当我执行脚本时,我只获取前三个文本框的数据。 I get in my database: 我进入我的数据库:

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

After weeks of doing research I have discovered that there is something wrong with the JavaScript part of the code. 经过数周的研究,我发现代码的JavaScript部分有问题。 When I send the data with the text boxes in the second example I get the result I want. 当我用第二个例子中的文本框发送数据时,我得到了我想要的结果。 When I use JavaScript to create the dynamic text boxes the PHP script will only post the first row (that is not created with JavaScript) to the database. 当我使用JavaScript创建动态文本框时,PHP脚本只会将第一行(不是用JavaScript创建)发布到数据库。

What is wrong with my script? 我的脚本出了什么问题?

Here is the script I am using to add data to my database: 这是我用来向我的数据库添加数据的脚本:

<?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');
    }
?>

Result of var_dump on $_POST['number'] : $_POST['number']var_dump结果:

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

The main problem is that all your fields in the form have the same name, even though they are supposed to be arrays, you're not really allowing for multiple rows. 主要问题是表单中的所有字段都具有相同的名称,即使它们应该是数组,也不是真的允许多行。

The easiest (not necessarily the optimal) way is to make some tweaks 最简单的(不一定是最优的)方式是进行一些调整

Change your form element names to 将表单元素名称更改为

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

and make sure your form changes the value for $i on each row, so that your form becomes: 并确保您的表单更改每行$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 />

and so on... Then, alter your form processing to iterate over $variable : 等等...然后,更改您的表单处理以迭代$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
}

that's it! 而已! Like I said, this is not necessarily the best way to accomplish your goal, but it is by far the easiest 就像我说的,这不一定是实现目标的最佳方式,但它是迄今为止最简单的方法

You can keep your form fields with the array names, but in order to post your data to the database, you will need to iterate through the array. 您可以使用数组名称保留表单字段,但是为了将数据发布到数据库,您需要遍历数组。

So your receiving page should collected all the form data in a $_POST variable, and then you can parse the posted values as $_POST['number'] and iterate through the array using a for-each loop. 因此,您的接收页面应该在$ _POST变量中收集所有表单数据,然后您可以将发布的值解析为$ _POST ['number']并使用for-each循环遍历数组。

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

    print_r($_POST['price']);
}

Dont inject pure html but play with DOM. 不要注入纯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 part looks almost OK: 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();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM