How to Use JSON Data Field in MySQL Database

Websolutionstuff | Jun-04-2021 | Categories : PHP MySQL

Today, In this post we will see how to use json field in mysql database. In this tutorial i will give mysql json data type example and we will see how to store json data in mysql using php.

here we will see differents type of json functions with example and we will see how to insert json data into mysql using php.

here, we are creating category table.

CREATE TABLE `post` (
  `id` MEDIUMINT(8) UNSIGNED NOT NULL AUTO_INCREMENT,
  `name` VARCHAR(200) NOT NULL,
  `category` JSON DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=INNODB;

 

Add JSON Data

JSON data can be passed in INSERT or UPDATE statements. For ex, our post category can be passed as an array (inside a string):

INSERT INTO `post` (`name`, `category`)
VALUES (
  'web developing',
  '["JavaScript", "PHP", "JSON"]'
);

 

JSON can also be created with these:

JSON_ARRAY()  function create arrays like this :

-- returns [1, 2, "abc"]:
SELECT JSON_ARRAY(1, 2, 'abc');

 

JSON_OBJECT() function create objects like this :

-- returns {"a": 1, "b": 2}:
SELECT JSON_OBJECT('a', 1, 'b', 2);

 

JSON_QUOTE() function quotes a string as a JSON value.

-- returns "[1, 2, \"abc\"]":
SELECT JSON_QUOTE('[1, 2, "abc"]');

 

JSON_TYPE() function allows you to check JSON value types. It should return OBJECT, ARRAY, a scalar type (INTEGER, BOOLEAN, etc), NULL, or an error

-- returns ARRAY:
SELECT JSON_TYPE('[1, 2, "abc"]');

-- returns OBJECT:
SELECT JSON_TYPE('{"a": 1, "b": 2}');

-- returns an error:
SELECT JSON_TYPE('{"a": 1, "b": 2');

 

JSON_VALID() function returns 1 if the JSON is valid or 0 otherwise.

-- returns 1:
SELECT JSON_TYPE('[1, 2, "abc"]');

-- returns 1:
SELECT JSON_TYPE('{"a": 1, "b": 2}');

-- returns 0:
SELECT JSON_TYPE('{"a": 1, "b": 2');

 

If you are insert an invalid JSON data then it will create an error and the whole record will not be inserted/updated.

 

Recommended Post
Featured Post
Laravel 9 Order By Query Example
Laravel 9 Order By Query Examp...

In this article, we will see laravel 9 order by query example. how to use order by in laravel 9.The orderBy me...

Read More

Mar-28-2022

How To Add Toastr Notification In Laravel
How To Add Toastr Notification...

In this tutorial, I will show you how to add toastr notification in laravel application. There are many types of no...

Read More

May-29-2020

How to Run Specific Seeder in Laravel 8
How to Run Specific Seeder in...

In this example, we will learn how to run a specific seeder in laravel 8. If you want to run only one seeder in laravel...

Read More

Jan-19-2022

How To Remove Column From Table In Laravel 10 Migration
How To Remove Column From Tabl...

In this article, we will see how to remove columns from a table in laravel 10 migration. Here, we will learn about...

Read More

Apr-26-2023