Serialize PHP Array to Database Without JSON

This article explains how to store a PHP array in a database without converting it to JSON. You will learn how to use PHP’s native serialization functions to convert arrays into a storable string format, how to save this data securely in a database, and how to reconstruct the original array when retrieving it.

Using PHP Native Serialization

The standard alternative to JSON in PHP is the native serialize() function. This function generates a byte-stream representation of a PHP array or object, which can then be stored as a string in a database column (typically of type TEXT or BLOB). To retrieve the array, you use the unserialize() function.

Step 1: Serializing the Array

To prepare your array for database storage, pass the array to the serialize() function.

// Define a sample PHP array
$userSettings = [
    'theme' => 'dark',
    'notifications' => true,
    'retries' => 3
];

// Serialize the array into a string
$serializedData = serialize($userSettings);

// Output will be a formatted string: 
// a:3:{s:5:"theme";s:4:"dark";s:13:"notifications";b:1;s:7:"retries";i:3;}
echo $serializedData;

Step 2: Storing in the Database

When inserting the serialized string into your database, use prepared statements to prevent SQL injection. The target database column should be configured as a TEXT or VARCHAR type.

// Example using PDO prepared statements
$db = new PDO('mysql:host=localhost;dbname=testdb', 'username', 'password');

$stmt = $db->prepare("INSERT INTO user_profiles (settings) VALUES (:settings)");
$stmt->execute([':settings' => $serializedData]);

Step 3: Unserializing the Data

When you fetch the record from the database, use the unserialize() function to convert the string back into a fully functional PHP array.

// Fetch the serialized string from the database
$stmt = $db->prepare("SELECT settings FROM user_profiles WHERE id = :id");
$stmt->execute([':id' => 1]);
$row = $stmt->fetch(PDO::FETCH_ASSOC);

// Convert back to PHP array
$originalArray = unserialize($row['settings']);

// Access the array values
echo $originalArray['theme']; // Outputs: dark

Important Considerations