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

可捕获的致命错误:第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.

我目前正在建立一个小而简单的推荐系统。 但是,我无法尝试返回单个用户拥有的推荐数量。 当一个新用户注册它时,它存储在名为“referid”的列中,并且那里的ID对应于引用他的用户名。 p>

但是,在尝试查找多少次时 在“referid”列中提到该用户的ID,然后回显它,我收到此错误: p>

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

我无法理解究竟是什么造成了这种情况。 我做了一个快速谷歌,我只能看到PDO与字符串或其他东西不兼容。 我之前没有使用过PHP和MYSQL,因此我不确定如何“不”使用PDO。 p>

 &lt;?php 
 $ checknumber = $  odb  - &gt;  prepare(“SELECT COUNT('referid')FROM`users` WHERE`ID` =:ID”); 
 $ checknumber  - &gt;  execute(array(':ID'=&gt; $ _SESSION ['ID'])); 
echo($ checknumber); 
?&gt; 
  code>  pre> 
 
 

非常感谢任何帮助。 p> div>

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: