Home > OS >  How to retrieve data from MySQL to JSON?
How to retrieve data from MySQL to JSON?

Time:03-05

I have a Symfony project where I want to store the all the rows from my MySQL table to JSON. Currently there are five rows in my table, but in my browser it only returns five empty values as {"results":[{},{},{},{},{}]}

I guess I have done something right, but not everything. What am I missing in my code?

#[Route('/budget/api', name: 'budget-api')]
public function index(Request $request, BudgetRepository $repository)
{
  $results = $repository->findAll();
  return $this->json(['results' => $results]);
}

CodePudding user response:

You can use the serializer or re-create the array yourself like that

$courses = $doctrine->getRepository(Course::class)->findByLikeTitle($search, $userId);
foreach ($courses as $key => $course) {
    $jsonCourses[$key]['title'] = $course->getTitle();
}
```

CodePudding user response:

You can achieve this by Using a Serializer to convert the array of objects into JSON. There are other ways to achieve this like using jsonResponse for example. But the serializer is the most robust way imo.

Example only:

use Symfony\Component\Serializer\SerializerInterface;

#[Route('/budget/api', name: 'budget-api')]
public function index(Request $request, BudgetRepository $repository, SerializerInterface $serializer)
{
  $results = $repository->findAll();
  $jsonResults = $serializer->serialize($results, 'json');
  
  //If you need to handle any circular references, you can use this..
  $jsonResults = $serializer->serialize($results, 'json', array(
        'circular_reference_handler' => function ($object) { return $object; },
  ));

  return $jsonResults;
}
  • Related