W3docs

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.

To save a PHP array to a MySQL database, you can use the json_encode() function to convert the array into a JSON string, and then use an INSERT or UPDATE statement to save the string into a JSON or TEXT field in the database.

Here is an example of how you can do this:

Example of saving PHP array to MySQL

<?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];

// Encode the array as JSON
$json_array = json_encode($array);

// Insert the JSON string into the database using a prepared statement
$stmt = $conn->prepare("INSERT INTO table_name (field_name) VALUES (?)");
$stmt->bind_param("s", $json_array);
if ($stmt->execute()) {
  echo "New record created successfully";
} else {
  echo "Error: " . $stmt->error;
}
$stmt->close();

// Close the connection
mysqli_close($conn);

?>

<div class="alert alert-info flex not-prose"> Watch a course <span class="hidden md:block">Watch a video course </span> Learn object oriented PHP</div>

When you retrieve the data from the database, you can use the json_decode() function to convert the JSON string back into an array.

Example of using json_decode() function in PHP

<?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 JSON string from the database
$stmt = $conn->prepare("SELECT field_name FROM table_name WHERE id = ?");
$id = 1;
$stmt->bind_param("i", $id);
$stmt->execute();
$result = $stmt->get_result();
$row = mysqli_fetch_assoc($result);

// Decode the JSON string
$array = json_decode($row['field_name'], true);

// Print the array
print_r($array);

$stmt->close();
mysqli_close($conn);

?>

Keep in mind that storing arrays as serialized strings is generally inefficient and not recommended for relational databases. It is better to store each element as a separate row, or use MySQL's native JSON type for structured data. Also, avoid using unserialize() on data from untrusted sources, as it can lead to security vulnerabilities. Note that this example uses procedural mysqli; for new projects, PDO is often preferred for its flexibility and consistent API.