How to insert array of data into mysql database using php

Lets say I have an Array that looks like below when output threw print_r(). So now i want to insert this array data in mysql database. 










NOTE : In this array key is the name of table
column. So below is the simple function to do this - 

Funtion :

function mysql_insert_array($table, $data, $exclude = array()) {
 // Change database setting with your's
 $conn = new mysqli('localhost', 'root', '');
 mysqli_select_db($conn,"YOUR_DATABASE_NAME");
 $fields = $values = array();
 if( !is_array($exclude) ) $exclude = array($exclude);
 foreach( array_keys($data) as $key ) {
  if( !in_array($key, $exclude) ) {
   $fields[] = "`$key`";
   $values[] = '"' . $data[$key] . '"';
  }
 }
 $fields = implode(",", $fields);
 $values = implode(",", $values);
 if( mysqli_query($conn, "INSERT INTO `$table` ($fields) VALUES ($values)") ) {
  return array( "mysql_error" => false,
       "mysql_insert_id" => mysqli_insert_id($conn),
       "mysql_affected_rows" => mysqli_affected_rows($conn),
       "mysql_info" => mysqli_info($conn)
     );
 } else {
  return array( "mysql_error" => mysqli_error($conn) );
 }
}

Method of uses -

$array_data = Array
 (
  [0] => Array
   (
    [name] => Bob
    [email] => bob@gmail.com
    [contact_no] => 874343434
   )
   
  [1] => Array
   (
    [name] => Dan
    [email] => dan@gmail.com
    [contact_no] => 9876343434
   )

  [2] => Array
   (
    [name] => Paul
    [email] => paul@yahoo.com
    [contact_no] => 9987343433
   )
   
  [3] => Array
   (
    [name] => Mike
    [email] => mike@gmail.com
    [contact_no] => 8877635353
   )  
 );


mysql_insert_array('users', $array_data);



Please don't forgot to leave a comment if you like this post. 

Chears :)
Happy Coding..

Post a Comment

Previous Post Next Post