简体   繁体   English

为什么此查询脚本返回致命错误?

[英]Why does this query script return a fatal error?

I get a fatal error on executing the query below: 我在执行以下查询时遇到致命错误:

$stmt = $db->query('SELECT * FROM comments LIMIT 50');
    while ($result = $stmt->fetch(PDO::FETCH_ASSOC)) {
        echo $result['name'] . ':' . strip_tags($result['message']);
    }

Returns: 返回值:

  Fatal error: Call to a member function query() on a non-object

I set my $db like this: 我这样设置$ db:

try {$db = new PDO('mysql:host=localhost;dbname=database', 'username', 'password');}
catch(PDOException $e) {echo $e->getMessage();}

Does anyone know what causes this error? 有人知道导致此错误的原因吗?

You are not getting an error because of the execution of the query. 由于执行查询,您没有收到错误。 The query in fact will never try to execute 该查询实际上永远不会尝试执行

This error - 这个错误-

Fatal error: Call to a member function query() on a non-object

tells you that $db is not an object. 告诉您$db不是对象。

Either it was never instantiated, or it was instantiated within a different scope. 要么从不实例化它,要么在另一个范围内实例化它。

$db has not been properly initialized in the scope you are using it. $ db尚未在您使用的范围内正确初始化。

You might want to try putting a global $db; 您可能想尝试放置global $db; before both of them to see if it is a scope problem. 他们俩先来看看这是否是示波器问题。

global $db;
try {$db = new PDO('mysql:host=localhost;dbname=database', 'username', 'password');}
catch(PDOException $e) {echo $e->getMessage();}

global $db;
$stmt = $db->query('SELECT * FROM comments LIMIT 50');
    while ($result = $stmt->fetch(PDO::FETCH_ASSOC)) {
        echo $result['name'] . ':' . strip_tags($result['message']);
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM