繁体   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?

所以我想插入数据库信息,但是输入字段的名称和值会动态变化,下面是代码的第一部分

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

一种选择是遍历$_POST并获取每个字段(键=字段的名称)。 下一步:您可以使用Prepared Statements来构建MySQL查询。


$_POST的内容可能如下所示:

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

提示:在每个字段名称之前添加前缀,以防止SQL查询中出现不需要的值。 但是请记住在查询中使用前缀时将其删除。

最后一步是构建并执行准备好的语句。 我在此示例中使用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();

我将假定表单中的字段名称也是表的列名称,这是一个简单的解决方案:

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

如果某些输入字段不是表的一部分,或者实际上在任何情况下都可以在字段形成部分中进行检查。 例如:

$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 ) . "',";
}

上面的代码未经测试,仅应用作参考。

暂无
暂无

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

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