php - MySQL: Selecting boolean value from JSON field -


i'm using mysql 5.7.19

i'm trying retrieve class looks follows

class task {     public $title;     public $done; } 

the title , done properties saved in json column.

the code use retrieve looks follows:

    $taskssql = <<<'eot'     select  json_unquote(json_extract(data, '$.title')) title,             json_extract(data, '$.done') done                 tasks tasklistid = ?; eot;     $tasksstatement = $connection->prepare($taskssql);     $tasksstatement->execute([$id]);     $tasksstatement->setfetchmode(pdo::fetch_class, "task");     $tasklist->tasks = $tasksstatement->fetchall(pdo::fetch_class, "task"); 

it fills out fields, done property gets set string values "true" or "false" instead of boolean value.

i think pdo not recognizing boolean value being returned, , assuming string. has nothing json being used. change in query

json_extract(data, '$.done') done 

into

json_extract(data, '$.done') = true done 

to change integer 0/1 instead.

or change php code parse returned value boolean. example adding constructor tasks object:

class task {     public $title; // string     public $done; // bool     // ...      public function __construct() {         $this->done = $done == 'true';     } } 

or let pdo use anonymous function conversion:

$tasklist->tasks = $tasksstatement->fetchall(pdo::fetch_func, function($title, $done) { $task = new task(); $task->title = $title; $task->done = $done == 'true'; return $task;}); 

Comments

Popular posts from this blog

networking - Vagrant-provisioned VirtualBox VM is not reachable from Ubuntu host -

c# - ASP.NET Core - There is already an object named 'AspNetRoles' in the database -

ruby on rails - ArgumentError: Missing host to link to! Please provide the :host parameter, set default_url_options[:host], or set :only_path to true -