Insert PHP Array into MySQL Table

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

This is a beginner tutorial on PHP and MySQL, You’ll learn here basic MySQL operations with PHP.

The following code will help to create a 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.

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

Also Checkout other dynamic MySQL query tutorials,

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 it into a PHP array, Next step is – we will implode all row data and prepare an insert SQL command to insert all PHP array data into the 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.

4 thoughts on “Insert PHP Array into MySQL Table

  1. One problem with serialized data is that it is not searchable via mysql query.. It is still better to insert each of the data one row each in the database table.

  2. Great! execpt
    the foreach($records as $row) is pointing to the values instead of to index.
    should be:
    foreach($records as $row =>$value)

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.