graham23s graham23s - 7 months ago 18
PHP Question

PDO error Cannot use object of type stdClass as array

I have been trying to learn PDO instead of MySQL when using PHP, i have a bit of code i can't see where the error is:

<?php

include('includes/db_connection.php');
include('includes/sessions.php');
include('includes/functions.php');
include('includes/header.php');
include('includes/loginnav.php');

$row = DB::getInstance()->selectOneByField('membership', 'username', $member);

$logged_in_users_id = $row['id'];

$result3 = DB::getInstance()->select('
SELECT *
FROM `pms`
WHERE `sender_id` = :logged_in_users_id
ORDER BY `date_added` DESC',
[
'logged_in_users_id' => $logged_in_users_id
]);

if (count($result3) == 0) {
stderr('No messages have been sent. (<a href="inbox.php">Inbox</a>)');
}

?>

<div class="panel panel-primary">
<div class="panel-heading">Sentbox</div>
<div class="panel-body">
<table class="table table-striped table-condensed table-responsive table-hover">
<thead>
<tr>
<th>Subject</td>
<th>Date Sent</td>
<th>To User</td>
<th>Read (<font color="green">Y</font>&nbsp;/&nbsp;<font color="red">N</font>)</td>
</tr>
</thead>
<tbody>
<?php foreach ($result3 as $row) { ?>
<?php
$id = $row['id'];
$sendee_id = $row['reciever_id'];
$read = $row['read_flag'];
$row = DB::getInstance()->selectOneByField('membership', 'id', $sendee_id);
$sendee = $row['username'];
$sendee_id = $row['id'];
$row_2 = DB::getInstance()->selectOneByField('pms', 'reciever_id', $logged_in_users_id, PDO::FETCH_OBJ);
?>
<tr>
<td><strong><?php echo htmlspecialchars($row_2['subject']) ?></strong></td>
<td><?php echo htmlspecialchars($row_2['date_added']) ?></td>
<td><a href="user-details.php?id=<?php echo $sendee_id ?>"><?php echo htmlspecialchars($sendee) ?></td>
<td style="color: <?php echo ($read == 'Y')? 'green': 'red' ?>"><strong><?php echo htmlspecialchars($read) ?></strong></td>
</tr>
<?php } ?>
</tbody>
</table>
</div>
</div>


The error: "PHP Fatal error: Cannot use object of type stdClass as array in" on line 52 which beging on this line:

<td><strong><?php echo htmlspecialchars($row_2['subject']) ?></strong></td>


I have tried to debug what the error is but i'm stuck at the minute, any help would be appreciated.

Answer

Try $row_2->subject instead of $row_2['subject']

When accessing StdClass objects use ->.