Reputation: 11
hello I want to print "title" in the menu content data in the database, but I get an error. I do not know much about json, but as a result of my research, something like this came out and the error code is below
Warning: Illegal string offset 'title' in menu.php on line 59
mysql database data menu_content
[{"title":"HelloWord","address":"HelloAdres","phone":"HelloPhone","submenu":[{"email":"HelloSubmenuEmail","phone":"HelloSubmenuPhone","fax":"HelloSubmenuFax"}]}]
pdo
$query = $db->prepare('SELECT * FROM menu ORDER BY menu_id DESC');
$query->execute();
$rows = $query->fetchAll(PDO::FETCH_ASSOC);
table
<tbody>
<?php foreach ($rows as $row): ?>
<tr data-id="<?= $row['menu_id'] ?>">
<td width="90"><?= $row['menu_id'] ?></td>
<td width="90"><?= $row['menu_title'] ?></td>
<td><?php json_decode($row['menu_content']['title'],true) ?></td>
<td><?= $row['menu_date'] ?></td>
</tr>
<?php endforeach; ?>
</tbody>
Upvotes: 0
Views: 87
Reputation: 620
Try is code :
<tbody>
<?php foreach ($rows as $row)
{
$menu_content=json_decode($row['menu_content'],true)
?>
<tr data-id="<?= $row['menu_id'] ?>">
<td width="90"><?= $row['menu_id'] ?></td>
<td width="90"><?= $row['menu_title'] ?></td>
<td><?= $menu_content[0]['title'];?></td>
<td><?= $row['menu_date'] ?></td>
</tr>
<?php
}
?>
</tbody>
Upvotes: 0
Reputation: 94662
You should convert the JSON column before attempting to make use of its parts.
<tbody>
<?php
foreach ($rows as $row):
$menu = json_decode($row['menu_content']);
?>
<tr data-id="<?= $row['menu_id'] ?>">
<td width="90"><?= $row['menu_id'] ?></td>
<td width="90"><?= $row['menu_title'] ?></td>
<td><?= $menu[0]->title ?></td>
<td><?= $row['menu_date'] ?></td>
</tr>
<?php
endforeach;
?>
</tbody>
Upvotes: 2