Insert PHP Array into MySQL Table

This is beginner tutorial of PHP and MySQL,In This post we will learn how to insert php array into mysql table. This is very common problem when we have multiple rows of data that we want to insert into MySQL as row.We can do very easily using php to insert array into MySQL.

Following code will help to create PHP function to insert array php data into mysql.For Ex, We have following php array.

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

Also Checkout other dynamic MySQL query tutorials,

We will follow below steps to insert arrays of data into mysql –

  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.

I am assuming – You have created table and connection with mysql, $conn is connection object,You need to replace 'programming_lang' with your table name and field.* with your column name.I haven’t taken any id for row, I am assuming you have auto incremented 'id' column in 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 step is – we will implode all row data and prepare insert SQL command to insert all php array data into MySQL table.

PHP also provide serialize() function to insert php array as string into mysql. You can store all php array into MySQL table as a string using serialize() and revert back php array using unserialize().

Conclusion

In This Post, We have learn how to insert PHP Array into MySQL database table using php. There are two option to insert php array into MySQL table.We can also store php array into MySQL table using php serialize() function.