9951 explained code solutions for 126 technologies


php-pdoInsert JSON into table with PHP PDO


We have test table with data text column which we will store data in JSON format.

$json = ['some' => 'value', 'key' => 'okay'];
$st = $pdo->prepare('INSERT INTO test SET data = :json');
$st->execute([':json' => json_encode($json)]);ctrl + c
$json

example array to save as JSON in the table

$pdo->prepare

prepare given query to execute

$st->execute(

run query on the server

json_encode($json)

we encode array to a JSON string to save it in the TEXT column


Usage example

<?php

$pdo = new PDO('mysql:host=localhost;dbname=test', 'usr', 'pwd');

$json = ['some' => 'value', 'key' => 'okay'];
$st = $pdo->prepare('INSERT INTO test SET data = :json');
$st->execute([':json' => json_encode($json)]);

echo $pdo->lastInsertId();
output
9