Array to string conversion error from result returned by PDO

Question

I'm getting errors because I converted from MySQL to PDO, after I changed to PDO, most of the line have solved, but one of them is related to string... I'm

getting error said

Array to string conversion in C:header.php on line 573

the line I'm getting errors is

<?php if($msg_cnt>0) { echo '('.$msg_cnt.')'; }?></i></a>

please see code on last two lines... how can i solve that!

<?php if(!isset($_SESSION['account_type'])){?><a href="#"><?php }?>


            <?php if(isset($_SESSION['account_type'])){ 

            $msg_cnt_q = $conn ->query("select * from messages where receiver_id='".$_SESSION['user_id']."' and receiver_read_status='unread'");
            $msg_cnt = $msg_cnt_q->fetch(PDO::FETCH_ASSOC);?>


            <a href="http://www.xxxxxx/inbox.php">

            <i class="fa fa-bell fa-lg fa-color" style="padding-top:17px;">

            <?php if($msg_cnt>0) { echo '('.$msg_cnt.')'; }?></i></a>

            <?php }?>

thanks for your time....


Show source
| pdo   | mysql   | string   2017-01-05 21:01 1 Answers

Answers ( 1 )

  1. 2017-01-05 21:01

    The error is a general PHP error when you try to print an array where you should have a single scalar value. Like concatenating the value with other strings.

    The PDO function fetch() returns an array containing a row of data, not the count of rows in the result set.

    PDO provides a different function rowCount() so you can know how many rows.

    $row = $msg_cnt_q->fetch(PDO::FETCH_ASSOC);
    $msg_cnt = $msg_cnt_q->rowCount();
    
◀ Go back