John Higgins John Higgins - 7 months ago 33
PHP Question

Insert form $_POST array into a MySQL database using mysqli

I have a $_POST array and I am trying to code an insert into a MySQL database without having to list through all the field names.

The array is a single row that needs to be inserted into the database.

The array looks like this:

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
)


I have coded the form field names to correspond with the field names in the database for ease.

Many thanks,

John

Answer

you can use this method :

NOTE :i use PDO

first connect to DB like:

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

hope this help

Comments