我有一个$ _POST数组,我正在尝试将插入代码编写到MySQL数据库中,而不必列出所有字段名称。
数组是需要插入数据库的单行。
数组如下所示:
Array
(
[membership_type] => 4
[title] => Mr
[first_name] => John
[last_name] => Smith
[known_as] => John
[address_1] => 10 High Street
[address_2] => Big House
[address_3] => Big Road
[address_4] => Chipping Sodbury
[address_5] => Bristol
[post_code] => BS37 1AB
[home_tel] => 01454 123456
[mobile] => 07777 123456
[email] => john@email.com
[confirm_email] => john@email.com
[day_dob] => 21
[month_dob] => 09
[year_dob] => 1974
[volunteer] => on
[employment_status] => employed
[college_nus] =>
[employment_address] => 50 Station Road
Chipping Sodbury
Bristol
BS37 2CD
[occupation] => Managerial/Professional
[employement_email] => john@work.com
[employement_phone] => 01454 654321
[terms] => 1
)
为了方便起见,我已将表单字段名称编码为与数据库中的字段名称相对应。
非常感谢,
约翰
答案 0 :(得分:2)
您可以使用此方法:
注意:我使用PDO
首先连接到DB,如:
$connection = new PDO('mysql:host=' . yourHost . ';dbname=' . youDbName . ';charset=utf8', DBUser, Dbpass);
$data=$_POST;
$bind = ':' . implode(',:', array_keys($data));
$field = explode(",", $bind);
$returnQuery = "INSERT INTO `tableName` (" . implode(",", array_keys($data)) . ") VALUES (" . $bind . ") ";
$bind = $connection ->prepare($returnQuery);
$bind->execute(array_combine($field, array_values($data)));
希望这个帮助
答案 1 :(得分:0)
您可能需要以下内容:
<?php
$query = "";
if(isset($_POST)){
foreach( $_POST as $key => $val ) {
$query .= " `$key`='$val', ";
}
$query = preg_replace('/,$/', '', $query); // removes the last comma
}
//$query: `name`='pedro', `email`='stack@stack.com'