Mysql
 sql >> Base de données >  >> RDS >> Mysql

Extraire des données de MySQL dans un tableau json

Si vous vouliez faire cela avec PDO, voici un exemple :

<?php 
$dbh = new PDO("mysql:host=localhost;dbname=DBNAME", $username, $password);

$sql = "SELECT `id`, `title`, `time`, `start`, `backgroundColor` 
        FROM my_table";

$result = $dbh->query($sql)->fetchAll(PDO::FETCH_ASSOC);
//To output as-is json data result
//header('Content-type: application/json');
//echo json_encode($result);

//Or if you need to edit/manipulate the result before output
$return = [];
foreach ($result as $row) {
    $return[] = [ 
        'id' => $row['id'],
        'title' => $row['title'],
        'start' => $row['start'].' '.$row['time'],
        'backgroundColor' => $row['backgroundColor']
    ];
}
$dbh = null;

header('Content-type: application/json');
echo json_encode($return);
?>