1

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();
}
?>`
Philipp Maurer
2,4886 gold badges20 silver badges26 bronze badges
asked Dec 13, 2017 at 13:11

2 Answers 2

2

Why dont you try the json_encode() for this ? Why you try for unnecessary while loop.

$query = $conn->prepare('SELECT id, name, salary from afreen');

Then try the json_encode() to get the Data in Json format.

Sources - http://php.net/json_encode

answered Dec 13, 2017 at 13:21
Sign up to request clarification or add additional context in comments.

Comments

0
<?php
header("Access-Control-Allow-Origin: *");
header('Content-type: application/json');
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()) {
 array_push($registros,array(
 'id' =>$result["id"],
 'title' =>$result["name"],
 'salary' =>$result["salary"]
 ));
 $output = json_encode(array("product"=>$registros));
 print_r($output);
} catch (Exception $e) {
 echo "Erro: " . $e->getMessage();
}
?>
answered Dec 13, 2017 at 13:22

3 Comments

Code dumps do not make for good answers. You should explain how and why this solves their problem. I recommend reading, "How do I write a good answer?"
Parse error: syntax error, unexpected 'catch' (T_CATCH) in C:\xampp\htdocs\appmarket-api\listado.php on line 25
try and catch remove and check output

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.