简体   繁体   English

如果输入字段是动态的并且输入名称总是变化并且数量变化,如何使用PHP将数据插入MySQL?

[英]How insert data into MySQL using PHP if input fields are dymanic and input names always change and the amount of them?

so i want to insert into database information but the input fields names and values change dynamically how would do this below is the first part of the code 所以我想插入数据库信息,但是输入字段的名称和值会动态变化,下面是代码的第一部分

echo'<form action="add3rd.php" method="post">';
while($row = mysqli_fetch_assoc($title2)) {
    echo '' . $row["input"]. '  <input type="text" name="' . $row["input"]. '">';
    echo '<input type="hidden" name="' . $row["input"]. '" value="' . $row["articleid"]. '">' ;

}
echo'<input type="submit" value="Next"></form>';
}  

One option is to loop through $_POST and get each field (key = the field's name). 一种选择是遍历$_POST并获取每个字段(键=字段的名称)。 Next: you can use Prepared Statements to build the MySQL query. 下一步:您可以使用Prepared Statements来构建MySQL查询。


Example

The content of $_POST may look like this: $_POST的内容可能如下所示:

[
    "name_of_field": "value",
    "name_of_another_field": "another value"
    // etc...
]

Tip: Put a prefix before every field name to prevent unwanted values in your SQL query. 提示:在每个字段名称之前添加前缀,以防止SQL查询中出现不需要的值。 But remember to remove the prefix when you use it in the query. 但是请记住在查询中使用前缀时将其删除。

The last step is to build and execute a prepared statement. 最后一步是构建并执行准备好的语句。 I am using PHP Data Objects (PDO) for this example. 我在此示例中使用PHP数据对象(PDO)

// The MySQL connection
$conn = new PDO("mysql:host={$host};dbname={$db}", $username, $password);

// Get the names of the fields from $_POST (I assume that the fieldnames are the same as the column names).
// Remember my tip that I wrote above.
$fieldNames = implode(',', array_keys($_POST));

// Get the values of the fields from $_POST
$fieldValues = implode(',', array_values($_POST));

// Prepare the query
$stmt = $conn->prepare("INSERT INTO YourTable ({$fieldNames}) 
VALUES ({$fieldValues})");

// Execute the query
$stmt->execute();

I will assume that the field names in the form are also column names of the table, a simplistic solution is this : 我将假定表单中的字段名称也是表的列名称,这是一个简单的解决方案:

$input_names  = '';
$input_values = '';

//Iterate the POST table to get the input names and values
foreach($_POST as $input_name => $input_value){
    // escaping is always important
    $input_names  .= mysqli_real_escape_string ( $con, $input_name ) . ",";
    $input_values .= "'" .mysqli_real_escape_string ( $con, $input_value ) . "',";
}
// Remove trailing comma
$input_names  = rtrim( $input_names, "," );
$input_values = rtrim( $input_values, "," );
$sql = "INSERT INTO table_name ( $input_names ) VALUES ( $input_values )";

if ( $con->query($sql) === TRUE ) {
    // Success
} else {
    // Failure
}

In case there are input fields that are not part of the table, or actually in any case a check can happen in the field forming part. 如果某些输入字段不是表的一部分,或者实际上在任何情况下都可以在字段形成部分中进行检查。 For example: 例如:

$field_array = ["field1", "field2", "field3"];
foreach($_POST as $input_name => $input_value){

    // Skip field if the name is not in the $field_array
    if(!in_array( $input_name, $field_array ){
        continue;
    }

    $input_names  .= mysqli_real_escape_string ( $con, $input_name ) . ",";
    $input_values .= "'" .mysqli_real_escape_string ( $con, $input_value ) . "',";
}

The above code is untested and should only be used as a reference. 上面的代码未经测试,仅应用作参考。

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

相关问题 PHP 和 MYSQL:插入带有 mysql 数据的输入选择并在更改选择时显示所有其他字段 - PHP and MYSQL: Insert input select with mysql data and show all other fields when change selection 如何遍历php中的多个动态输入字段以将它们插入到mysql表中? - How to loop through multiple dynamic input fields in php to insert them in mysql table? 使用AJAX从php文件中获取多个数据并将其插入不同的输入字段中 - Fetch multiple data from a php file using AJAX and insert them in different input fields 我如何使用php将输入字段数组插入mysql - How do i insert an array of input fields into mysql with php 如何使用php向MySQL中插入/更新大量数据 - How to insert/update a large amount of data into mysql using php 如何基于MySQL值更改PHP中的输入字段数? - How to change the number of input fields in PHP based on a MySQL value? 使用php将大量数据插入mysql - using php insert huge amount of data into mysql 如何使用PHP将输入数组表单字段插入数据库表 - How to Insert Input Array Form Fields into a Database Table using PHP 使用PHP将“输入类型文本”作为日期插入到MySQL数据库中 - insert 'input type text' as date to mysql data base using php 当输入字段的数量和名称不同时,如何确保MySQL插入的列匹配? - How to insure column match for MySQL insert, when number and names of input fields will vary?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM