【问题标题】:Insert one or more sets of fields into database using dynamic form使用动态表单将一组或多组字段插入数据库
【发布时间】:2017-10-01 21:25:37
【问题描述】:

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

没有动态内容一切正常。在我将我的 html 表单从 city 更改为 city[] 后,它显然停止将数据传递到我的数据库。

我尝试了各种方法来完成这项工作,但没有成功。有什么想法吗?

表单操作:

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

表单数据检索与查询:

<?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")
?>

表格:

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

【问题讨论】:

    标签: php jquery html forms mysqli


    【解决方案1】:

    $date['$key'] 应该是 $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 as $key => $name) {
        $age = $date[$key];
        $stmt->execute();
    }
    

    【讨论】:

    • 当我尝试它时,它会给我一个服务器错误(“si”代表什么?)
    • si 代表第一列是字符串,第二列是整数。
    • 此页面无法正常工作 www.orastravelagency.com 目前无法处理此请求。 HTTP 错误 500
    • 对于我的测试,我将年龄列作为文本字段留下了这有关系吗?
    • 我将其更改为 ss 以匹配它,尽管值是否为数字可能并不重要。 MySQL 会自动转换。
    【解决方案2】:

    您的流程中存在一些问题。

    您想生成多个输入字段,并将它们作为数组存储在$_POST 中。

    改变这个:

    但是,您写的属性不正确,$_POST 没有读取 id 的:

    <input type="text" name="city" id="city[]">
    <input type="text" name="date" id="date[]">
    

    到这里:

    <input type="text" name="city[]">
    <input type="text" name="date[]">
    

    我已删除您的 id 属性,因为您的页面中不应/不能有重复的 id。如果您需要为 css 识别这些字段,则使用它们的 name 属性或添加 class 属性来识别它们。

    当您在 javascript 中动态添加后续内容时,您应该再次使用 name=city[]name=date[];并删除 id。

    这将导致您的 $_POST 数组按预期成为一个正确填充的多维数组。

    $name=$_POST['name'];  // this is a string
    $cities=$_POST['city'];  // this is an array
    $dates=$_POST['date'];  // this is an array
    

    如果您不打算在查询中包含city,我真的不明白为什么在您的表单中 - 所以我将它包含在我的解决方案中。而且您的表格列的名称并不直观,因此请考虑将它们更改为更能代表要存储的值的名称。

    $stmt=$mysqli->prepare("INSERT INTO employe_table (`name`,`city`,`date`) VALUES (?,?,?)");
    $stmt->bind_param("sss",$name,$city,$date);
    foreach($cities as $index=>$city){
        $date=$dates[$index];
        $stmt->execute();
    }
    

    在编程时,始终努力制作DAMP and DRY 的作品——它将成倍地帮助你和任何看到它的人。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-04-14
      • 1970-01-01
      • 1970-01-01
      • 2015-06-21
      • 2019-01-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多