Calling a member function () on a non-object

I am getting this error:

Calling a member function () on a non-object.

Also when I use other MySQLi functions it gives me the same error but for this function.

My connection.php

:

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

?>

      

My function:

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);
}

      

Function and connection are enabled when the function is called

+3


source to share


4 answers


Quick / dirty fix:



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

      

+7


source


You can try to remove the comma after Type

as it might be a syntax error for the MySQL string. Also try echo $mysqli->error

and see what it says.



+1


source


Your object $mysqli

is in global scope, not in function scope. You must pass the mysqli

function object as a parameter so that you can access it. So something like this:

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

      

Note. I would also add some check in the function to make sure the correct mysqli object was sent, but this is not shown.

+1


source


You have to make sure your $ mysqli is in scope (which is not your function). Several solutions are available: global, passing arguments, singleton. Personnaly I usually make a singleton to connect to a database, something like this:

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);

      

0


source







All Articles