Shubham Mehta
Shubham Mehta

Reputation: 89

How to resolve the illegal string offset error and display the table in the following code snippet?

I am trying to display data from my MySQL local database using the following PHP and markup.

<html>
<table>
<tr>
    <th>field1</th>
    <th>field2</th>
    <th>field3</th>
</tr>
<?php
$dbh = new PDO("mysql:host=localhost;dbname=dbtest", 'root', 'root');
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sth = $dbh->prepare("SELECT `fruit_id`, `name`, `variety` FROM fruit");
$sth->execute();
?>
<?php foreach($sth->fetch(PDO::FETCH_ASSOC) as $row) : ?>
<tr>
    <td><?php echo $row["fruit_id"]; ?></td>
    <td><?php echo $row["name"]; ?></td>
    <td><?php echo $row["variety"]; ?></td>
</tr>
<?php endforeach;?>
</table>

I'm getting Illegal String Offset errors for the same. Also I guess due to those I'm not able to display my table as well. I'm new at handling databases using PHP and I really looked at the other questions concerning Illegal String Offset errors too before posting my own but due to my beginner level expertise I wasn't quite able to understand the answers. Could anyone please help me remove the errors and display the table?

Upvotes: 0

Views: 435

Answers (1)

Mani
Mani

Reputation: 2655

Use $sth->fetchAll() in foreach, because $sth->fetch() will return only single row only.

<?php foreach($sth->fetchAll() as $row) : ?>

Upvotes: 1

Related Questions