Добавить к массиву массива php mysql

Insert Array into MySQL Database using PHP

Today, let’s see how to store and retrieve arrays into the database using PHP and MySQL. MySQL’s databases don’t accept objects or array data types. The array value directly inserts into the MySQL database, not support. But you can convert an array into a string. Four ways to insert an array into a MySQL database.

MySQL database

Create a database called devooti and create a table called list with fields:

 
devooti
CREATE TABLE `list` ( `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT, `name` varchar(80) NOT NULL, `country` varchar(255) NOT NULL, `status` varchar(255) NOT NULL, `details` longtext COLLATE utf8mb4_unicode_ci NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8;

Method 1) Insert PHP Array into MySQL database using Repetitive.

 
index.php
array("Tricia Allison", "USA", "True"), "1" => array("Karla Newman", "China", "True"), "2" => array("Jessica Munoz", "UK", "False") ); if(is_array($user_data)) < foreach ($user_data as $row) < $val1 = mysqli_real_escape_string($db_conn, $row[0]); $val2 = mysqli_real_escape_string($db_conn, $row[1]); $val3 = mysqli_real_escape_string($db_conn, $row[2]); $query ="INSERT INTO list (name, country, status) VALUES ( '".$val1."','".$val2."','".$val3."' )"; mysqli_query($db_conn, $query); >> ?>

Output

Method 2) Insert PHP Array into MySQL database table using onetime.

 
index.php
array("Tricia Allison", "USA", "True"), "1" => array("Karla Newman", "China", "True"), "2" => array("Jessica Munoz", "UK", "False") ); if(is_array($user_data)) < $DataArr = array(); foreach($user_data as $row)< $val1 = mysqli_real_escape_string($db_conn, $row[0]); $val2 = mysqli_real_escape_string($db_conn, $row[1]); $val3 = mysqli_real_escape_string($db_conn, $row[2]); $DataArr[] = "('$val1', '$val2', '$val3')"; >$sql = "INSERT INTO list (name, country, status) values "; $sql .= implode(',', $DataArr); mysqli_query($db_conn, $sql); > ?>

Output

Method 3) To Convert Array into serialized string

We can convert the array to string with serialized function and converting string to array using serialize () function and then insert into the database. Here’s the PHP code to do it.

 
index.php
array("Tricia Allison", "USA", "True"), "1" => array("Karla Newman", "China", "True"), "2" => array("Jessica Munoz", "UK", "False") ); $serialized_data = serialize($user_data); $sql = "insert into list (details) value ('$serialized_data')"; mysqli_query($db_conn, $sql); ?>

Output

Retrieve data from the database and convert into an array

Output

Array ( [0] => Array ( [0] => Tricia Allison [1] => USA [2] => True ) [1] => Array ( [0] => Karla Newman [1] => China [2] => True ) [2] => Array ( [0] => Jessica Munoz [1] => UK [2] => False ) )

Читайте также:  Убираем отступы

Method 4) To Convert Array into JSON string

We can convert the array to JSON string with json_decode() function and convert a JSON string to array using json_decode() function and then insert into the database. Here’s the PHP code to do it.

 
index.php
array("Tricia Allison", "USA", "True"), "1" => array("Karla Newman", "China", "True"), "2" => array("Jessica Munoz", "UK", "False") ); $json_data = json_encode($user_data); $sql = "insert into list (details) value ('$json_data')"; mysqli_query($db_conn, $sql); ?>

Output

[[“Tricia Allison”,”USA”,”True”],[“Karla Newman”,”China”,”True”],[“Jessica Munoz”,”UK”,”False”]]

Retrieve JSON data from the database

Output

Array ( [0] => Array ( [0] => Tricia Allison [1] => USA [2] => True ) [1] => Array ( [0] => Karla Newman [1] => China [2] => True ) [2] => Array ( [0] => Jessica Munoz [1] => UK [2] => False ) )

Conclusion

In These tutorials, we have learned how to store and retrieve arrays into the database using PHP and MySQL. There are two ways to insert a PHP array into a MySQL table database, using serialize() and unserialize() function.

  • How to Store Array in MySQL with PHP
  • How to Enter PHP Array within MySQL Database
  • Store & Retrieve Arrays Into Database With PHP MYSQL
  • PHP Insert Array
  • Array value insert into PHP MySQL Database
  • How to insert multiple array values into database PHP
  • Insert multiple arrays values into a MySQL table
  • I want to inserting multiple array values in PHP
  • Insert into array php Code Example
  • Insert an item at a specific position in an array in PHP
  • Learn PHP Array Push: PHP Add to Array Explained
  • Array push key value pair php
  • php array push key value Code Example
  • PHP insert into array at index 0
  • Insert array into one column mysql
  • In mysql insert array values in one column
  • Save Array into one column

Recent Posts

  • Updated Angular, Asp.net Core 3, Entity Framework Core 3 July 14, 2022
  • Asp.net Core, Angular, And Bootstrap In Front-end Development July 14, 2022
  • hands-on and pragmatic journey to master Angular with Typescript July 14, 2022
  • Reactive Patterns with RxJS for Angular: A practical guide to managing your Angular application’s data reactively and efficiently using RxJS 7 July 14, 2022
  • Pro Angular: Build Powerful and Dynamic Web Apps July 14, 2022
  • The Basics Of Html, Css And Some Intermediate To Advanced Coding In A Fast Paced, Detailed System July 14, 2022
  • Developing Database-Driven Websites With PHP 7, MySQL 8 & MariaDB July 14, 2022
  • PHP: PHP Security and Session Management July 14, 2022
  • An Instruction to HTML, CSS, PHP, and MySQL To Create Data-Driven Web Sites July 14, 2022
  • PHP: Advanced PHP functions July 14, 2022
  • Design Patterns In PHP & Laravel Using Real-world Examples July 14, 2022
  • HP: 3 Books in 1: PHP Basics for Beginners + PHP Security and Session Management + Advanced PHP Functions July 14, 2022
  • Html, Css, Php, Bootstrap, Javascript And Mysql To Create A Dynamic Site July 14, 2022
  • Advanced Javascript Design Patterns July 14, 2022
  • How To Code in React.js July 14, 2022
  • Docker, Node.js, React, Typescript & Webpack To Develop Modern Full-stack July 14, 2022
  • React App vs NextJS July 14, 2022

Источник

How to Store Array in MySQL with PHP

An array is a special variable that allows storing one or more values in a single variable e.g. – holding usernames or details in an Array.

They are easier to access and manipulate.

Sometimes, require to store Array in the MySQL database and retrieve it.

In this tutorial, I show how you can store an Array in the MySQL database and read it with PHP.

How to Store Array in MySQL with PHP

Contents

1. Table structure

Create contents_arr table.

The ‘arr_serialize1’ and ‘arr_serialize2’ is used to store serialized value.

CREATE TABLE `contents_arr` ( `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT, `username` varchar(80) NOT NULL, `name` varchar(80) NOT NULL, `arr_serialize1` varchar(255) NOT NULL, `arr_serialize2` varchar(255) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8;

2. Configuration

Create a config.php for the database connection.

Completed Code

3. With serialize() and unserialize()

Define two arrays – $names_arr , and $users_arr .

$names_arr Array is Indexed type Array and $users_arr is an Associative Array.

Serialize Syntax –

Pass the array in the serialize() method and pass the serialized values in the INSERT query.

Unserialize Syntax –

unserialize([Serialized value]);

Fetch records and pass the serialized value in the unserialize() method to convert it to Array format.

Completed Code

"yssyogesh","name"=>"Yogesh singh"); $users_arr[] = array("username"=>"bsonarika","name"=>"Sonarika Bhadoria"); $users_arr[] = array("username"=>"vijay","name"=>"Vijay Maurya"); // Serialize the Array $names_str = serialize($names_arr); $users_str = serialize($users_arr); // Insert record $sql = "INSERT INTO contents_arr(arr_serialize1,arr_serialize2) VALUES('".$names_str."','".$users_str."')"; mysqli_query($con,$sql); // Read record $sql = mysqli_query($con,"SELECT * FROM contents_arr"); while($row = mysqli_fetch_assoc($sql))< // Unserialize $arr_unserialize1 = unserialize($row['arr_serialize1']); $arr_unserialize2 = unserialize($row['arr_serialize2']); // Display echo "
"; print_r($arr_unserialize1); print_r($arr_unserialize2); echo "

«; >

Array ( [0] => Yogesh singh [1] => Sonarika Bhadoria [2] => Vijay Maurya ) Array ( [0] => Array ( [username] => yssyogesh [name] => Yogesh singh ) [1] => Array ( [username] => bsonarika [name] => Sonarika Bhadoria ) [2] => Array ( [username] => vijay [name] => Vijay Maurya ) )

4. With implode() and explode()

Use implode() to separate the $names_arr by separator (” , “) and get a string. Pass the value in the INSERT query.

Fetch records and use explode() to convert a comma-separated string in an Array format.

In the example, I am displaying the value in a string and Array format.

Completed Code

"; echo "
"; print_r($name_explode); echo "

"; >

name : Yogesh singh , Sonarika Bhadoria , Vijay Maurya Array ( [0] => Yogesh singh [1] => Sonarika Bhadoria [2] => Vijay Maurya )

5. With Loop

Loop on the $users_arr Array.

Read and pass the value in the INSERT query. New record is inserted until data is available.

Completed Code

"yssyogesh","name"=>"Yogesh singh"); $users_arr[] = array("username"=>"bsonarika","name"=>"Sonarika Bhadoria"); $users_arr[] = array("username"=>"vijay","name"=>"Vijay Maurya"); // Insert record foreach($users_arr as $userid=>$user) < $username = $user['username']; $name = $user['name']; $sql = "INSERT INTO contents_arr(username,name) VALUES('".$username."','".$name."')"; mysqli_query($con,$sql); >// Read record $sql = mysqli_query($con,"SELECT * FROM contents_arr"); while($row = mysqli_fetch_assoc($sql))< $username = $row['username']; $name = $row['name']; echo "username : ".$username.", name : ".$name."
"; >
username : yssyogesh, name : Yogesh singh username : bsonarika, name : Sonarika Bhadoria username : vijay, name : Vijay Maurya

6. Conclusion

It is better to use serialize() method which converts an Array to string format and stores it in a single column. You need to use the unserialize() method to convert the serialized value and get it back in the Array format.

If you found this tutorial helpful then don’t forget to share.

Источник

Как сделать запись php массива в mysql

Для того чтобы записать php массив в MySQL, необходимо использовать функцию mysqli_query() . Данная функция позволяет выполнять запросы к базе данных. Например, для того, чтобы записать массив в MySQL, можно использовать следующий запрос:

 $sql = "INSERT INTO table_name (field1, field2, . ) VALUES (value1, value2, . )"; $result = mysqli_query($connection, $sql); if ($result)  echo "Запись успешно добавлена в базу данных"; > else  echo "Ошибка при добавлении записи в базу данных: " . mysqli_error($connection); > 

Здесь переменная $connection содержит подключение к базе данных, а переменная $sql содержит запрос INSERT .

Для вставки значений из массива в запрос можно использовать цикл foreach .

Источник

Оцените статью