在非对象上调用成员函数query()

时间:2013-01-28 23:19:29

标签: php mysqli

我收到此错误:

  

在非对象上调用成员函数query()。

此外,当我使用其他MySQLi函数时,它给出了同样的错误,但对于该函数。

我的connection.php

<?php
$mysqli = new mysqli("localhost","user","pass","db");
if(mysqli_connect_errno()){
  trigger_error('Connection failed: '.$mysqli->error);
}

?>

我的功能:

function form_year($find, $value, $from, $vehicletype){
    //Query setup
    $autoquery = "SELECT    
                        Year, 
                        Vehicle, 
                        Brand, 
                        Model, 
                        Type, 
                    FROM 
                        vehicle_tbl
                    WHERE
                        Vehicle = '".$vehicletype."'
                    GROUP BY
                        Year";
    $autoresult = $mysqli->query($autoquery);

    $search = array("%value%", "%options%");
    $rows = file_get_contents("tpl/options.html");
    while($row = $autoresult->fetch_assoc()){
        $replace = array($row[$value], $row[$value]);
        $tr .= str_replace($search, $replace, $rows);
    }
    return str_replace($find, $tr, $from);
}

函数和连接包含在调用函数的位置

4 个答案:

答案 0 :(得分:7)

快速/脏修复:

  function form_year($find, $value, $from, $vehicletype){
    //Query setup
    global $mysqli;
    $autoquery = "SELECT  [...]

答案 1 :(得分:1)

您可能希望尝试删除Type之后的逗号,因为这可能是MySQL字符串的语法错误。同时尝试回应$mysqli->error并查看其内容。

答案 2 :(得分:1)

您的$mysqli对象在全局范围内,而不在函数范围内。您应该将mysqli对象作为参数传递给函数,以便您可以访问它。所以像这样:

function form_year($find, $value, $from, $vehicletype, $db){
    ...
    $autoresult = $db->query($autoquery);
    ...
}

注意我还会在函数中添加一些验证,以确保传递了正确的mysqli对象,但是没有显示。

答案 3 :(得分:0)

你必须确保你的$ mysqli在范围内可用(在你的函数中不是这种情况)。一些可用的解决方案:全局,传递参数,单例。 Personnaly我通常为我的数据库连接做单例,类似的东西:

class DB {
private static $_instance;

public static function get() {
    if(!isset(self::$_instance)) {
        self::$_instance = new mysqli("localhost","user","pass","db");
        if(mysqli_connect_errno()) {
            trigger_error('Connection failed: '.self::$_instance->error);
        }
    }
    return self::$_instance;
}
}

//Calling

$autoresult = DB::get()->query($autoquery);