Jump to content

Warning: mysqli_query() expects parameter 1 to be mysqli, null given in ...


alirezan82

Recommended Posts

Hello

 

I am writing a simple API functions for my php website and I am getting this error when I'm starting to test it for mysqli_query. Here is the code:

<?php

class Globals {
    public $isConnected2DB;
    public $conn;
}

$BCKCGlobals = new Globals();
 
 function init () {
 
    $BCKCGlobals->isConnected2DB = false;
 }

 function ConnectDB ($SQlserver, $DB, $user, $pass) {
    
    $con=mysqli_connect($SQlserver,$user,$pass,$DB);

    // Check connection
    if (mysqli_connect_errno())
    {
        echo "Failed to connect to Database: " . mysqli_connect_error();
        return false;
    }
    $BCKCGlobals->conn = $con;
    $BCKCGlobals->isConnected2DB = true;
    return true;
 }
 
 function CloseDB () {
    if ( $BCKCGlobals->isConnected2DB && $BCKCGlobals->conn ) {
        mysqli_close($BCKCGlobals->conn);
    }
 }

 function getConnection () {
    if ( $BCKCGlobals->isConnected2DB && $BCKCGlobals->conn ) {
        return $BCKCGlobals->conn;
    } else {
        init();
        ConnectDB(localhost, website, user, pass);
        return $BCKCGlobals->conn;
    }
 }
 
 function ReadDB ( $table, $columns ) {
    $q = "SELECT ". $columns . " FROM " . $table;
    echo $q;
    
    $result = mysqli_query($BCKCGlobals->conn, $q);
    return $result;
 }

init();

ConnectDB(localhost, website, user, pass);

$result = ReadDB("contents", "*");

while($row = mysqli_fetch_array($result))
  {
  echo $row['content'];
  echo "<br>";
  }

?>

Any ideas what I'm doing wrong?

It looks like your problem is scope. You have $BCKCGlobals that you attempt to set and reference in various functions, but that variable doesn't exist within the scope of the functions. You need to pass the variable by reference or value to your functions, or else declare that you want to reference the globally scoped variable, by putting this at the top of all your functions that set or reference it:

 

global $BCKCGlobals;
Note: the latter method is generally not a good idea.

It looks like your problem is scope. You have $BCKCGlobals that you attempt to set and reference in various functions, but that variable doesn't exist within the scope of the functions. You need to pass the variable by reference or value to your functions, or else declare that you want to reference the globally scoped variable, by putting this at the top of all your functions that set or reference it:

 

global $BCKCGlobals;
Note: the latter method is generally not a good idea.

 

 

Worked! Thanks!

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.