douwang4374 2012-11-22 17:32
浏览 116
已采纳

可捕获的致命错误:第30行的/home/refined/public_html/refer.php中无法将类PDOStatement的对象转换为字符串

I currently am building a small and simple referral system. However I am having trouble trying to return how many referrals one single user has. When a new user registers it stores in a column called "referid" and that ID in there correspond to the ID of the username who referred him.

However, upon attempting to find how many times that user's ID is mentioned in the "referid" column and then echoing it, I get this error:

Catchable fatal error: Object of class PDOStatement could not be converted to string in /home/refined/public_html/refer.php on line 30

I cant understand what's actually causing this. I did a quick google and all I could see was that PDO isn't compatible with strings or something. I haven't used PHP and MYSQL together that much before so I'm not sure how to "not" use PDO.

<?php
$checknumber = $odb -> prepare("SELECT COUNT('referid') FROM `users` WHERE `ID` = :ID");
$checknumber -> execute(array(':ID' => $_SESSION['ID']));
echo($checknumber);
?>

Any help is very much appreciated.

  • 写回答

1条回答 默认 最新

  • douweng1904 2012-11-22 17:40
    关注

    Let's analyse your code:

    $checknumber = $odb -> prepare("SELECT COUNT('referid') FROM `users` WHERE `ID` = :ID");
    

    ... where PDO::prepare() is defined as:

    PDOStatement PDO::prepare ( string $statement [, array $driver_options = array() ] )

    So it returns an object. But two lines later you try to print the object:

    echo($checknumber);
    

    If you check any of the usage examples in the manual you'll see that you need to call one of the PDOStatement methods to extract the query results, e.g.:

    <?php
    /* Execute a prepared statement by passing an array of values */
    $sql = 'SELECT name, colour, calories
        FROM fruit
        WHERE calories < :calories AND colour = :colour';
    $sth = $dbh->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));
    $sth->execute(array(':calories' => 150, ':colour' => 'red'));
    $red = $sth->fetchAll();
    

    Update: Two more links:

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?