是的...这个问题已多次发布。这是一个例子:Fatal error: Call to a member function query()on a non-object。但我查看了很多这些重复的帖子,找不到解决方案
我从这个网站(nine-to-five)
中提取了这个(工作)代码但我修改了我的代码(与SO帖子不同),以包含帖子答案中提到的代码,我仍然收到错误:
// Credentials
$dbhost = "localhost";
$dbname = "qmsdb";
$dbuser = "root";
$dbpass = "";
// Connection
global $tutorial_db;
$tutorial_db = new mysqli();
$tutorial_db->connect($dbhost, $dbuser, $dbpass, $dbname);
$tutorial_db->set_charset("utf8");
// Check Connection
if ($tutorial_db->connect_errno) {
printf("Connect failed: %s\n", $tutorial_db->connect_error);
exit();
}
// Get Search
$search_string = preg_replace("/[^A-Za-z0-9]/", " ", $_POST['query']);
$search_string = $tutorial_db->real_escape_string($search_string);
// Check Length More Than One Character
if (strlen($search_string) >= 1 && $search_string !== ' ') {
// Build Query
$query = 'SELECT * FROM compressors WHERE MUNPN LIKE "%'.$search_string.'%" OR name LIKE "%'.$search_string.'%"';
// Do Search
$result = mysql_query($query);
while($results = $result->fetch_array()) {
$result_array[] = $results;
}
.... more code that doesn't apply....
}
错误是:“对非对象的成员函数fetch_array()的致命调用”,该行指向:
while($results=$results->fetch_array()) {
我对Php / MySQL很新 - 所以对此的任何帮助都将非常感激。
谢谢!
答案 0 :(得分:1)
mysql_*()
函数 NOT , NEVER 是面向对象的:
$tutorial_db = new mysqli();
^----note the "i"
$result = mysql_query($query);
^-- note the LACK of an "i"
while($results = $result->fetch_array()) {
^^^^^^^^---- not an object, because mysql_*() functions are NOT objects
您不能在任何其他库中使用在一个数据库库(pdo,mysqli,mysql)中创建的数据库句柄/对象。他们可能都在谈论MySQL,但他们各自的句柄/对象不是互相兼容的。