Insert PHP Array into MySQL Table

his is novice educational of PHP and MySQL, on this submit we will learn how to insert PHP array into MySQL table. this is very commonplace trouble while we have more than one rows of statistics that we need to insert into MySQL as row.we can do very effortlessly the usage of PHP to insert an array into me.

Following code will help to create PHP characteristic to insert array PHP facts into me.For Ex, we’ve following PHP array.


$records = array(
"0" => array("Parvez", "Alam", "123"),
"1" => array("Affan", "Alam", "344"),
"2" => array("Ajay", "Sharma", "22")
);

I want to insert above PHP array into MySQL database table.We have Two option to insert PHP array into MySQL using PHP.

  1. Using Repetitive Insert command on each row
  2. Using Single Insert command by concatenating all array values into array

Option 1: PHP Insert Array into MySQL Using Repetitive Insert Command

Here we will iterate on each row of data and execute separate insert command for each row.


if(is_array($records)){
foreach ($records as $row) {
$fieldVal1 = mysql_real_escape_string($records[$row][0]);
$fieldVal2 = mysql_real_escape_string($records[$row][1]);
$fieldVal3 = mysql_real_escape_string($records[$row][2]);
$query ="INSERT INTO programming_lang (field1, field2, field3) VALUES ( '". $fieldVal1."','".$fieldVal2."','".$fieldVal3."' )";
mysqli_query($conn, $query);
}
}

I am assuming you have created table and connection with MySQL, $conn is connection item, You need to update‘programming_lang’ along with your table name and subject.* with your column call.I haven’t taken any identity for the row, ‘m assuming you have automobile incremented ‘identification‘ column to your table.

Option 2: PHP Insert Array into database table Using Single Insert Command

In this option, we will parse all rows data and store into PHP array, next, we will implode all row data and prepare to insert command to insert all PHP array into MySQL table.

if(is_array($records)){


$DataArr = array();
foreach($records as $row){
$fieldVal1 = mysql_real_escape_string($records[$row][0]);
$fieldVal2 = mysql_real_escape_string($records[$row][1]);
$fieldVal3 = mysql_real_escape_string($records[$row][2]);

$DataArr[] = "('$fieldVal1', '$fieldVal2', '$fieldVal3')";
}

$sql = "INSERT INTO programming_lang (field1, field2, field3) values ";
$sql .= implode(',', $DataArr);

mysqli_query($conn, $query);
}

PHP also provides theserialize() function to insert PHP array as the string into me.You can store all PHP array into MySQL table as a string using andserialize() revert back PHP array using.unserialize()

Please follow and like us:



Leave a Comment

Your email address will not be published. Required fields are marked *