![](/img/trans.png)
[英]PHP and MYSQL: Insert input select with mysql data and show all other fields when change selection
[英]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.