成员函数非对象

时间:2013-05-13 00:30:53

标签: php fatal-error

我制作了一个简单的mysqli函数包装器,用于连接。当我尝试使用它时,我收到致命错误

"Fatal error: Call to a member function query() on a non-object in /home/cgateams/public_html/home.cga/test.php on line 5"

Line 5: $res = $dblink->query("select * from test");

test.php的

include('includes/db/config.php');

$dblink = db_connect();
$res = $dblink->query("select * from test");
while ($res = $row) {
    echo $row['test'];
}

的config.php

//Database server
$host = 'localhost';
$dbname = 'dbname';  //sanitized data
$dbuser = 'dbuser';
$dbpass = 'dbpass';

// db connect to nm database
function db_connect()
{
    global $host, $dbuser, $dbpass, $dbname;

   $dbconnect = new mysqli($host, $dbuser, $dbpass, $dbname);

   if (!dbconnect)
     throw new Exception('Could not connect to CGA database currently');
   else
   return $dbonnect; 
}

3 个答案:

答案 0 :(得分:4)

你错过了$。它应该是:

if (!$dbconnect)

然后在返回值中进一步下降,你有一个拼写错误:

return $dbconnect;

你得到的错误是因为没有返回你的mysqli对象(因为拼写错误)。

另外,看一下使用mysqli的预处理语句 - 它们非常强大,比内联查询更安全,特别是当你进入params时。

答案 1 :(得分:3)

db_connect()函数中,您将返回$dbonnect。它应该是$dbconnect

答案 2 :(得分:0)

config.php中出现错误:if (!dbconnect)if (!$dbconnect)