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
Set vi as the default editor in Ubuntu — a terminal opening the vim editor
How to Set vi (Vim) as the Default Editor in Ubuntu
June 8, 2026
rsync says ALL DONE but files are missing — a terminal showing ALL DONE next to an empty folder
rsync Says “ALL DONE” but Files Are Missing: How to Verify
June 8, 2026
Migrate a website to a new server with rsync — files copying from an old server to a new one over SSH
How to Migrate a Website to a New Server With rsync
June 8, 2026
Bun runtime — faster JS toolkit replacing npm in Laravel projects
How to Install Bun Runtime on Ubuntu (And Use It in a Laravel Project)
May 24, 2026
Tailscale mesh — peer-to-peer connections between devices, coordination server
How to Install Tailscale on Ubuntu (Zero-Config Mesh VPN for Self-Hosters)
May 24, 2026

You Might Also Like

Laravel get config variable — config() helper and Config facade resolving dotted keys
Web Development

How to Get Config Variables in Laravel

7 Min Read
Extract a .tar.gz archive in PHP with PharData
Web Development

How to Extract a .tar.gz Archive in PHP

5 Min Read
Laravel old() helper for repopulating form inputs
Web Development

How Laravel’s old() Helper Works (and Why It Sometimes Doesn’t)

6 Min Read
WordPress wp_dequeue_style priority 9999 runs after plugin enqueues
Web Development

How to Deregister or Remove a CSS File in WordPress (wp_dequeue_style Not Working)

6 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?