Geraldo Isaaks
Geraldo Isaaks

Reputation: 156

mysqli_query(): Couldn't fetch mysqli

I've been checking on this error with no solutions specific to my code. I have connected to mysql server using the mysqli_connect() call. then passed the connection result to a $_SESSION to have it available over the whole website - as i normally do in all my other projects, But for some reason i keep getting the error:

"mysqli_query(): Couldn't fetch mysqli"

There is the code that generates the error:

if(!isset($_GET['sortBy']))
    {
        $listSQL = "SELECT * FROM '".$_SESSION['WorkTable']."'";
    }
    else
    {
        $listSQL = "SELECT * FROM '".$_SESSION['WorkTable']."' where ".$_GET['sortBy']."='".$_GET['sortBy']."'";
    }

    //get Contacts From DB
    if(!empty(mysqli_query(@$_SESSION['IMWEDBcxn'],$listSQL)))

Here is the connection class code...

if(!empty($cxn))
{
    $_SESSION['WorkTable'] = $dbTable;

    $_SESSION['IMWEDBcxn'] = $cxn;
}

Anything I'm missing here?

Upvotes: 0

Views: 529

Answers (1)

Shotgun
Shotgun

Reputation: 678

As stated by Ivan Solntsev, do not store a connection handler in a user's session for 2 obvious reasons :

1- Handlers can not be serialized.

2- Anything you store in a user's session (using $_SESSION), would only be available under that user's scope. I suggest you read more about sessions and PHP, $_SESSION is not a way to store data over sessions.

So doing something like :

$connect = mysqli_connect("...");
$_SESSION["dbconnection"] = $connect;

mysqli_query($_SESSION["dbconnection"], $query);

IS WRONG!

If you want a persistent connection, to avoid reconnecting on each DB query, read about MySQLi and Persistent connections : http://php.net/manual/en/mysqli.persistconns.php . If you are running on a PHP version under 5.3, I'd recommend using PDO (which I'd recommend regardless of the PHP version you're using).

Upvotes: 2

Related Questions