使用动态表单将一组或多组字段插入到数据库中 [英] Insert one or more sets of fields into database using dynamic form

查看:138
本文介绍了使用动态表单将一组或多组字段插入到数据库中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我在同一个问题上的第二篇文章,在我使用 mysql 而不是 mysqli 的第一篇文章中,所以我根据建议做了一些更新。
我有一个由用户通过javascript控制的可变字段集(1到20集)的表单。



没有动态内容,所有工作都很好。在将我的html表单从 city 更改为 city [] 后,它显然停止将数据传递到我的数据库。



我尝试了各种方法使这项工作没有成功。任何想法?



表单操作:

  var i = 0; //全局变量i 
//增量函数
函数increment(){
i + = 1;


$(document).ready(function(e){
///变量
var html ='< p />< div> ;';
html + ='< label for =city>城市:< / label>';
html + ='< input type =textname =childcity [] id =city>';
html + ='< label for =date>日期:< / label>;
html + ='< input type =text name =childdate []id =date>';
html + ='< a href =#id =removecity>移除城市< / a>';
html + ='< / div>';

var maxRows = 20;
// var x = 1;

//行
$(#addcity)。click(function(e){
if(i <= maxRows){
$(#container)。append(html);
+++ ;
}
});

//删除行
$(#container)。on('click','#removecity',function e){
$(this).parent('div')。remove();
i--;
});
});

表单数据检索和查询:

 <?php 
/ *尝试MySQL服务器连接。假设你使用默认设置(用户'root'没有密码)运行MySQL
服务器* /

$ mysqli = new mysqli(localhost,root,, pb1646a_jos1\" );

//检查连接

//转义用户输入的安全性

$ city = $ _POST ['city'];
$ date = $ _POST ['date'];

foreach($ city AS $ key => $ value){
//尝试插入查询执行
$ sql =INSERT INTO employe_table(name,age)
VALUES(
'。$ mysqli-> real_escape_string($ value)。',
'。$ mysqli-> real_escape_string($ date ['$ key'])。 '
);
$ insert = $ mysqli-> query($ query);
}
$ mysqli-> close(); //关闭连接
header(location:http://www.orastravelagency.com/modules/mod_pari/test/index.html)
?>

表格:

 <!DOCTYPE html> 
< html lang =en>
< head>
< script src =https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js>< / script>
< script src =java.jstype =text / javascript>< / script>
< meta charset =UTF-8>
< title>添加记录表格< /标题>
< / head>
< body>
< form action =insert2.phpmethod =post>
< div>
< p>
< label for =name>旅程名称:< / label>
< input type =textname =nameid =name>
< / p>
< / div>
< div id =container>
< p>
< label for =>城市:< / label>
< input type =textname =cityid =city []>
< label for =date>日期:< / label>
< input type =textname =dateid =date []>
< a href =#id =addcity>添加城市< / a>
< / p>
< / div>
< p />
< input type =submitvalue =submit>
< / form>
< / body>
< / html>


解决方案

$ date ['$键'] 应该是 $ date [$ key] 。引号阻止了 $ key 变量的计算,它使用 $ key 作为文字索引。



但您应该使用准备好的语句而不是连接变量。

  $ city = $ _POST ['city']; 
$ date = $ _POST ['date'];

$ stmt = $ mysqli-> prepare(INSERT INTO employe_table(name,age)VALUES(?,?));
$ stmt-> bind_param(ss,$ name,$ age);
foreach($ city为$ key => $ name){
$ age = $ date [$ key];
$ stmt-> execute();
}


This is my second post on the same issue, in my first post I was using mysql instead of mysqli so I have made some updates according to recommendations. I have a form with variable sets of fields (1 to 20 sets) controlled by the user via javascript.

Without the dynamic content all works well. After I changed my html form from city to city[] it obviously stopped passing the data to my database.

I have tried all sorts of ways to make this work with no success. Any ideas?

Form manipulation:

var i=0; //Global Variable i
//function for increment
function increment(){
    i +=1;
}

$(document).ready(function(e){
    /// Variables
    var html ='<p /><div>';
        html+='<label for="city">City:</label>';
        html+=' <input type="text" name="childcity[]" id="city">';
        html+=' <label for="date">Date:</label>';
        html+=' <input type="text" name="childdate[]" id="date">';
        html+='<a href="#" id="removecity">Remove City</a>';
        html+='</div>';

    var maxRows = 20;
    // var x = 1;

    // Rows
    $("#addcity").click(function(e){
        if(i <= maxRows){
            $("#container").append(html);
            i++;
        }
    });

    // Remove Rows
    $("#container").on('click','#removecity', function(e){
        $(this).parent('div').remove();
        i--;
    });
});

Form data retrieval and querying:

<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */

$mysqli = new mysqli("localhost", "root", "", "pb1646a_jos1");

// Check connection

// Escape user inputs for security

$city = $_POST['city'];
$date = $_POST['date'];

foreach($city AS $key => $value){
    // attempt insert query execution
    $sql = "INSERT INTO employe_table(name,age)
    VALUES (
        '".$mysqli->real_escape_string($value)."',
        '".$mysqli->real_escape_string($date['$key'])."'
    )";
    $insert = $mysqli->query($query);
}
$mysqli->close();    // Close connection
header("location: http://www.orastravelagency.com/modules/mod_pari/test/index.html")
?>

Form:

<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> 
<script src="java.js" type="text/javascript"></script>
<meta charset="UTF-8">
<title>Add Record Form</title>
</head>
<body>
<form action="insert2.php" method="post">
    <div>
    <p>
        <label for="name">Trip Name:</label>
        <input type="text" name="name" id="name">
    </p>
    </div>
    <div id="container">
    <p>
        <label for="">City:</label>
        <input type="text" name="city" id="city[]">
        <label for="date">Date:</label>
        <input type="text" name="date" id="date[]">
        <a href="#" id="addcity">Add City</a>
    </p>
    </div>
    <p />
    <input type="submit" value="submit">
</form>
</body>
</html>

解决方案

$date['$key'] should be $date[$key]. The quotes are preventing the $key variable from being evaluated, it's using $key as the literal index.

But you should use a prepared statement rather than concatenating variables.

$city = $_POST['city'];
$date = $_POST['date'];

$stmt = $mysqli->prepare("INSERT INTO employe_table(name, age) VALUES (?, ?)");
$stmt->bind_param("ss", $name, $age);
foreach ($city as $key => $name) {
    $age = $date[$key];
    $stmt->execute();
}

这篇关于使用动态表单将一组或多组字段插入到数据库中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆