How7o
  • Home
  • Tools
  • Prank Screens
  • Learn
  • Blog
  • Contact
Reading: How to Store a PHP Array in a MySQL Database
Share
How7oHow7o
Font ResizerAa
  • OS
Search
  • Home
  • Tools
  • Prank Screens
  • Learn
  • Blog
  • Contact
Follow US
© 2024–2026 How7o. All rights reserved.
How7o > Free Laravel, PHP, WordPress & Server Tutorials > Web Development > How to Store a PHP Array in a MySQL Database
Web Development

How to Store a PHP Array in a MySQL Database

how7o
By how7o
Last updated: May 23, 2026
5 Min Read
Store a PHP array in a MySQL database with JSON
SHARE

To store a PHP array in a MySQL database, serialize it to a string with json_encode() and write it into a JSON column (MySQL 5.7+, MariaDB 10.2+) or a TEXT/LONGTEXT column on older versions. Read it back with json_decode($value, true). PHP’s own serialize() works too but produces PHP-only data — JSON is the portable choice.

Contents
  • Schema
  • Insert with json_encode
  • Read with json_decode
  • PHP serialize() alternative
  • Query inside the JSON
  • When to normalize instead
  • Frequently asked questions
  • Related guides
  • References

Last verified: 2026-05-17 on PHP 8.3 with MySQL 8.0 and MariaDB 10.11. Originally published 2023-02-08, rewritten and updated 2026-05-17.

Schema

-- Modern: native JSON column (MySQL 5.7+, MariaDB 10.2+)
CREATE TABLE items (
    id    INT AUTO_INCREMENT PRIMARY KEY,
    name  VARCHAR(255) NOT NULL,
    tags  JSON
);

-- Legacy: TEXT / LONGTEXT
CREATE TABLE items (
    id    INT AUTO_INCREMENT PRIMARY KEY,
    name  VARCHAR(255) NOT NULL,
    tags  LONGTEXT
);

The native JSON type validates the value on insert (reject malformed JSON) and unlocks MySQL’s JSON functions. For new tables, use it.

Store PHP array in MySQL — json_encode/decode, JSON column type, normalize when querying

Insert with json_encode

$pdo  = new PDO('mysql:host=localhost;dbname=mydb;charset=utf8mb4', $user, $pass);
$array = ['apple', 'banana', 'cherry'];

$stmt = $pdo->prepare('INSERT INTO items (name, tags) VALUES (?, ?)');
$stmt->execute(['Fruit Box', json_encode($array)]);

Read with json_decode

$stmt = $pdo->prepare('SELECT name, tags FROM items WHERE id = ?');
$stmt->execute([42]);
$row = $stmt->fetch(PDO::FETCH_ASSOC);

// The second arg `true` returns associative arrays instead of stdClass objects
$tags = json_decode($row['tags'], true);
// ['apple', 'banana', 'cherry']

PHP serialize() alternative

$serialized = serialize(['apple', 'banana', 'cherry']);
// Store $serialized as a TEXT column...

$array = unserialize($serialized);
// Back to ['apple', 'banana', 'cherry']

Works, but the format is PHP-only — Node.js, Python, Go can’t read it without a port of PHP’s serializer. Avoid for any data that might be read outside PHP. JSON is the universal format.

Query inside the JSON

-- Find rows where the tags array contains 'banana'
SELECT * FROM items
WHERE JSON_CONTAINS(tags, '"banana"');

-- Extract a single value from inside the JSON
SELECT name, JSON_EXTRACT(tags, '$[0]') AS first_tag
FROM items;

The native JSON functions let you reach inside stored JSON without parsing it in PHP. Useful for filtering — but if you find yourself doing this often, the data probably wants its own normalized table.

When to normalize instead

  • Storing JSON is right for opaque blobs treated as a single unit — user preferences JSON, third-party API responses, audit-log payloads.
  • Normalize into a separate table when you’ll query, filter, sort, or join on individual values inside the array. tag as its own table with a tag_id foreign key in a join table gives you indexed lookups and proper aggregation.

Frequently asked questions

JSON or PHP serialize() — which should I pick?

JSON. It’s a universal format any language can read; PHP’s serialize() output is PHP-specific and breaks for other languages reading the same database. JSON also gives you MySQL’s native JSON functions (JSON_EXTRACT, JSON_TABLE, generated columns, JSON path indexes) for querying inside the array. Use serialize() only when you must preserve PHP-specific types like objects with private properties.

Should I use the JSON column type or a TEXT/LONGTEXT column?

MySQL 5.7+ and MariaDB 10.2+ have a native JSON type that validates the value on insert and lets you index and query inside the document. For new tables, prefer JSON. For legacy schemas where you can’t migrate, TEXT or LONGTEXT still works — JSON_EXTRACT works on a TEXT column too as long as the content is valid JSON.

When should I normalize into a separate table instead?

Whenever you need to query by individual array values. A relational table with one row per item lets you index, join, and aggregate. JSON storage is right for opaque blobs you treat as a single unit — user preferences, JSON-formatted metadata from a third-party API, audit-log payloads. If you find yourself parsing JSON in PHP to filter results, normalize.

How big can the column get?

TEXT holds 64 KB, MEDIUMTEXT 16 MB, LONGTEXT 4 GB. The JSON column type follows similar limits internally. For practical purposes, keep individual JSON values under 64 KB — anything bigger probably belongs in a different table (or a blob storage outside the database).

Related guides

  • How to Combine Two Arrays Without Duplicates in PHP
  • How to Get the Last Item from an Array in PHP
  • How to Combine Multiple Columns as One String in MySQL

References

PHP json_encode(): php.net/manual/en/function.json-encode.php. MySQL JSON type: dev.mysql.com/doc/refman/8.0/en/json.html. MariaDB JSON functions: mariadb.com/kb/en/json-functions.

TAGGED:arraysjsonmysqlphp

Sign Up For Daily Newsletter

Be keep up! Get the latest breaking news delivered straight to your inbox.
[mc4wp_form]
By signing up, you agree to our Terms of Use and acknowledge the data practices in our Privacy Policy. You may unsubscribe at any time.
Share This Article
Facebook Copy Link Print
Previous Article Stop cron job output and the resulting email spam How to Stop Cron Output (and the Spam Emails)
Next Article Submit a form with jQuery How to Submit a Form Using jQuery
Leave a Comment

Leave a Reply Cancel reply

You must be logged in to post a comment.

FacebookLike
XFollow
PinterestPin
InstagramFollow
Most Popular
Run Laravel queue workers with Supervisor
How to Run Laravel Queue Workers in Production with Supervisor
May 23, 2026
Nginx as a reverse proxy for a Node.js app on Ubuntu
How to Set Up Nginx as a Reverse Proxy for Node.js on Ubuntu
May 23, 2026
Install and configure Redis on Ubuntu for Laravel and WordPress
How to Install and Configure Redis on Ubuntu (for Laravel & WordPress)
May 23, 2026
Harden a fresh Ubuntu VPS with UFW, Fail2Ban, and SSH key auth
How to Harden a Fresh Ubuntu VPS: UFW + Fail2Ban + SSH Key Auth
May 23, 2026
Set up Let's Encrypt SSL with Certbot on Ubuntu
How to Set Up Let’s Encrypt SSL with Certbot on Ubuntu (Apache & Nginx)
May 23, 2026

You Might Also Like

WordPress logged-in menu swap — register_nav_menus + wp_nav_menu with is_user_logged_in ternary
Web Development

How to Display Different Menus to Logged-In Users in WordPress

7 Min Read
Replace Broken Images Automatically with JavaScript
Web Development

Replace Broken Images Automatically with JavaScript (and jQuery)

5 Min Read
Validate an email address in PHP with filter_var
Web Development

How to Validate an Email Address in PHP

5 Min Read
Laravel Blade Time Format (HH:MM)
Web Development

How to Show Only Hours and Minutes in Laravel Blade (HH:MM)

3 Min Read
How7o

We provide tips, tricks, and advice for improving websites and doing better search.

Tools

  • Age Calculator
  • Word Counter
  • Image Upscaler
  • Password Generator
  • QR Code Generator
  • See all tools→

Pranks

  • Fake Blue Screen Prank
  • Hacker Typer
  • Fake iMessage Generator
  • Windows XP Crash Prank
  • Windows 11 Update Prank
  • See all prank screens →

Company

  • About Us
  • Blog
  • Contact
  • Privacy Policy
  • Terms of Service
  • Sitemap
© 2024–2026 How7o. All rights reserved.
Welcome Back!

Sign in to your account

Username or Email Address
Password

Lost your password?