BobbyP
BobbyP

Reputation: 2245

Cant pass mysqli connection to class

I am trying to pass an mysqli database connection to a php class. The code I have so far (cut down for simplicity) is as follows:

db.php

$db_host = 'localhost';
$db_name = 'dbname';
$db_user = 'username';
$db_password = 'password';

$db = array('db_host'=>$db_host, 
    'db_name'=>$db_name, 
    'db_user'=>$db_user,
    'db_password'=>$db_password);

$dbCon = new mysqli( $db['db_host'], 
    $db['db_user'], 
    $db['db_password'], 
    $db['db_name']);

if (mysqli_connect_errno())
{
    die(mysqli_connect_error()); //There was an error. Print it out and die
}

index.php

<?php
    require_once($_SERVER["DOCUMENT_ROOT"] . "/db.php");

    $sql = "SELECT id FROM usr_clients";
    $stmt = $dbCon->prepare( $sql );
    if ($stmt)
    {
        $stmt->execute();
        $stmt->bind_result($id);
        while($stmt->fetch())
        {
            $cl = new Client($id, $dbCon);
            $cl->doIt();
        }
        $stmt->close();
    }
?>

client.php

<?php
    Class Client
    {
        private $con;
        public static $clientCount = 0;

        public function __construct( $id, $con )
        {
            $this->con = $con;

            $sql = "SELECT id FROM usr_clients WHERE id = $id";
            $stmt = $this->con->prepare( $sql );

            if ($stmt)
            {
                echo "it worked!";
            }
            else
            {
                echo "it failed";
            }
        }
}
?>

Now the index.php page successfully recognises the database connection declared in db.php, and returns a list of all clients. It then loops through each client, and creates a "client" object, passing it the database connection.

It is here that the problem seems to start. In the client class, the database connection is not recognised. I get multiple errors on the page saying "it failed". In the logs, there is a line about calling prepare() on a non object.

Can anyone explain why the connection works in index.php, but not in the client class?

Thanks

Upvotes: 1

Views: 859

Answers (1)

Your Common Sense
Your Common Sense

Reputation: 157839

Your main problem is assumptions.

You are assuming that there is no connection passed, judging by indirect consequence.

But a programmer should be always logically correct in their reasoning.

Talking of connection? Verify the very connection. var_dump($con) in the constructor. var_dump($this->con) in the method. If it fails - only now you can blame connection and start for the solution.
If not - there is no reason in looking for another connection passing method. Yet it's time to find the real problem.

If your query fails, you have to ask mysql, what's going on, using $this->con->error, as this function will provide you with a lot more useful information than simple "it fails". The right usage I've explained here: https://stackoverflow.com/a/15447204/285587

Upvotes: 1

Related Questions