When I pull data from the hello database, it just writes the first line, not the other lines, what could be the reason? I did not know much about php json but did not get any results.
İD 88 NOT FOUND
**database print **
[{"title":"facebook","contact":"facebook adres"}, {"title":"twitter","contact":"twitter adres"}]
database data
id:87 [{"title":"facebook","contact":"facebook adres"}, {"title":"twitter","contact":"twitter adres"}] id:88 [{"title":"instagram","contact":"instagram adres"}, {"title":"google","contact":"google adres"}]
database function
function menu($menu_title) { global $db; $query = $db->prepare('SELECT * FROM menu WHERE menu_title = :menu_title'); $query->execute([ 'menu_title' => $menu_title ]); $result = $query->fetchAll(PDO::FETCH_ASSOC); if ($result) { $data = []; foreach ($result as $key => $value) { $data += json_decode($value['menu_content'], true); } return $data; } return null; }
socialmedia foreach
<?php foreach (menu('sosyalmedya') as $key => $menu): ?> <?= $menu['title'] ?><br> <?= $menu['contact'] ?><br> <?php endforeach; ?>
Advertisement
Answer
You’re only returning the first element of each JSON array. Append the whole array to the result.
foreach ($result as $value) { $data = array_merge($data, json_decode($value['menu_content'], true)); }
BTW, don’t use SELECT *
if you only want the menu_content
column. Use SELECT menu_content
.