D
D
Dmitry Baibukhtin2014-07-10 01:48:43
PHP
Dmitry Baibukhtin, 2014-07-10 01:48:43

What is the best way to handle the result?

Goodnight. Tell me please. I have MySQL table A. This table has field A1. This field stores data in JSON. Where would it be more correct to decode this value?
Let's say there is a table
Tasks
id (int) | name (text) | params (text/json)
1 Option
Get data from the table and manually decode the params field only when its values ​​are needed
For example:

$query = mysql_query('SELECT * FROM `tasks`');
while($task = mysql_fetch_assoc($query))
{
    $taskParams = json_decode($task['params']);
    echo $taskParams['time_start'];
}

Option 2
We get data from the table, create an object for each row, which will automatically process the fields, so as not to do it manually all the time
. For example:
class Task 
{
    public $id;
    public $name;
    public $params;
    
    function __construct($task)
    {
        $this->id = $task['id'];
        $this->name = $task['name'];
        $this->params = json_decode($task['params']);
    }
}

$query = mysql_query('SELECT * FROM `tasks`');
while($taskOriginal = mysql_fetch_assoc($query))
{
    $task = new Task($taskOriginal);
    echo $task->params['time_start'];
}

These are the simplest examples to get an idea.
I like the second option better. How would you do?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey, 2014-07-10
@PiloTeZ

Option 2, but without public properties - everything is hardcore through getters and setters. Ideally, I would even block the constructor using a proxy class. But seriously, I would take Doctrine.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question