user116046
user116046

Reputation: 13

Php call to member function query() on a non-object error

I'm using mysqli for a function, and I'm getting an error, Fatal error: Call to a member function query() on a non-object in /home/u250000297/public_html/forum/system/db.php on line 46 I've tried different things, but I just get different errors, what am I doing wrong and where is my error?

Code lines 45-51:

function fetch($query) {
    $sql = $mysqli->query($query);
    $result =  $sql->fetch_array(MYSQLI_BOTH);
    return $result;
    $sql->free();

}

Here's my previous attempt and error : Warning: mysqli_query() expects parameter 1 to be mysqli, null given in /home/u250000297/public_html/forum/system/db.php on line 46 Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, null given in /home/u250000297/public_html/forum/system/db.php on line 47 Warning: mysqli_query() expects parameter 1 to be mysqli, null given in /home/u250000297/public_html/forum/system/db.php on line 46 Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, null given in /home/u250000297/public_html/forum/system/db.php on line 47

Code, lines 45-51:

 function fetch($query) {
    $sql = mysqli_query($mysqli, $query);
    $row = mysqli_fetch_array($sql, MYSQLI_BOTH);
    return $row;
    mysqli_free_result($row);

}

Connection:

$mysqli = mysqli_connect($this->host,$this->username,$this->password);
    mysqli_select_db( $mysqli,$this->database );
    if ($mysqli->connect_error) {
trigger_error('Database connection failed: '  . $mysqli->connect_error, E_USER_ERROR);

}

Upvotes: 0

Views: 1135

Answers (2)

suchitra nair
suchitra nair

Reputation: 555

Points to debug are

1) Is the connection to the database getting established?

2) Are your query strings correct?

Call to a member function query() on a non-object and Warning: mysqli_query() expects parameter 1 to be mysqli means that the $mysqli is null or isn't initialized properly. To get more information check the mysql error logs.

Upvotes: 0

Axel Amthor
Axel Amthor

Reputation: 11096

Either you need to define $mysqli as global or pass it as an argument. After a return, no statement will be executed (mysqli_free).

Global:

function fetch($query) {
    global $mysqli;

    $sql = $mysqli->query($query);
    $result =  $sql->fetch_array(MYSQLI_BOTH);


    return $result;


}

Parameter (and even better):

function fetch($myslqi, $query) {

    $sql = $mysqli->query($query);
    $result =  $sql->fetch_array(MYSQLI_BOTH);


    return $result;


}

Upvotes: 1

Related Questions