Iam trying to create a JSON object out of my SQL data in PHP. How to do that? This is my approach, which does not work so far.
<?php header("Access-Control-Allow-Origin: *"); header('Content-Type: text/html; charset=utf-8'); $dns = "mysql:host=localhost;dbname=afreen"; $user = "root"; $pass = ""; try { $conn = new PDO($dns, $user, $pass); if (!$conn) { echo "Not connected"; } $query = $conn->prepare('SELECT id, name, salary from afreen'); $query->execute(); $registros = "["; while ($result = $query->fetch()) { if ($registros != "[") { $registros .= ","; } $registros .= '{"id": "' . $result["id"] . '",'; $registros .= '"name": "' . $result["name"] . '"}'; $registros .= '"salary": "' . $result["salary"] . '"}'; $registros .= "]"; echo $registros; } catch (Exception $e) { echo "Erro: " . $e->getMessage(); } ?>`