Insert an array into a MySQL database using PHP

Today, we will learn simple ways to insert an array into a MySQL database using PHP. This is a very common use case where we have an array that we want to store in the database table.

We can’t insert an array into the database directly so we need to convert an array into a string. Here, we’ll explain two ways to convert an array into a string and easily retrieve it from the MySQL database using PHP.

Two ways to insert an array into a MySQL database

  1. Convert an array into serialized string
  2. Convert an array into JSON string

First of all, we will take one PHP array that contains the user data as follows.

1. Convert an array into serialized string

We can convert an array into serialized string and convert back from the serialized string to array using serialize() and unserialize() functions. Now, we will insert the PHP array after converting it into a serialized string using the serialize() function.

Fetch data from the database and convert into an array

2. Convert an array into JSON string

Using the json_encode() function, we can convert an array into JSON string and the json_decode() function used for converting JSON to an array. We recommend you to use the json method which is simple and accessible by javascript and other languages.

Fetch data from the database and convert into an array

That’s it for today.
Thank you for reading. Happy Coding..!!

If you found value in this article,
you can support us by buying me a coffee! ☕

You may also like...

1 Response

  1. pharmacie says:

    It’s very trouble-free to find out any matter on net as compared to textbooks, as I found this article at this website.

Leave a Reply

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