0

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>
2
  • $row['menu_content'] has the JSON, not title. Also return that to a variable, otherwise it won't do anything for you. Commented Jun 29, 2020 at 15:39
  • What have you tried to debug the problem? Commented Jun 29, 2020 at 15:49

2 Answers 2

2

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>
Sign up to request clarification or add additional context in comments.

4 Comments

so how do i get a submenu email ?
For example $menu[0]->submenu[0]->email But as its an array I assume you may have more than one so another foreach loop would be in order
RiggsFolly are you there?
@Mesut If you have a different question you should make a new post.
0

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>

3 Comments

A good answer includes an explanation of what problem the code solves and why and not just "try this".
Inventor Bala are you there?
Yes, Mesut. Tell me what you want.

Your Answer

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.