Save PHP array to MySQL?
To save a PHP array to a MySQL database, you can use the serialize()
function to convert the array into a string, and then use an INSERT
or UPDATE
statement to save the string into a TEXT
or LONGTEXT
field in the database.
Here is an example of how you can do this:
<?php
// Connect to the database
$conn = mysqli_connect('localhost', 'username', 'password', 'database_name');
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// Define the array
$array = [1, 2, 3, 4, 5];
// Serialize the array
$array = serialize($array);
// Insert the serialized array into the database
$sql = "INSERT INTO table_name (field_name) VALUES ('$array')";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
// Close the connection
mysqli_close($conn);
?>
Watch a video course
Learn object oriented PHP
When you retrieve the data from the database, you can use the unserialize()
function to convert the serialized string back into an array.
<?php
// Connect to the database
$conn = mysqli_connect('localhost', 'username', 'password', 'database_name');
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// Select the serialized array from the database
$sql = "SELECT field_name FROM table_name WHERE id = 1";
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_assoc($result);
// Unserialize the array
$array = unserialize($row['field_name']);
// Print the array
print_r($array);
// Close the connection
mysqli_close($conn);
?>
Keep in mind that this method of storing an array in a MySQL database is not very efficient, and it is not the recommended way of storing arrays in a database. It is generally better to store each element of the array as a separate row in the database.