1

I am calling a function from a second PHP file and I want to avoid creating the DB connection again. I am using this code but it does not work.

$Db = mysqli_init();
$Db->options(MYSQLI_OPT_LOCAL_INFILE, true);
$Db->real_connect($servername, $username, $password, $dbname, 3306);
$connection = $Db->real_connect($servername, $username, $password, $dbname, 3306);

CheckTableMetrics($connection, $dbname, $table1, $table2, $metric1, $metric2, $date1, $date2, $start_date, $end_date);

I get errors out of the blue. If I put the first part of my code in the PHP file that contains the function everything works.

The errors I get :

mysqli::query(): invalid object or resource mysqli

and

Call to a member function fetch_assoc() on a non-object

The code works fine if I just put the :

$Db = mysqli_init();
$Db->options(MYSQLI_OPT_LOCAL_INFILE, true);
$Db->real_connect($servername, $username, $password, $dbname, 3306);

Which is the best way to do it?

5
  • 2
    Does not work.. I love questions like these.. How are we magically supposed to know why it doesn't work? Turn on your error reporting and try to debug your code?! Commented Dec 15, 2015 at 12:33
  • 2
    What is it does not work? Commented Dec 15, 2015 at 12:33
  • try to use php.net/manual/en/class.pdo.php Commented Dec 15, 2015 at 12:36
  • You can create a singleton object for dbConnection. Also check this document -> stackoverflow.com/a/11369679/767329 Commented Dec 15, 2015 at 12:37
  • Please show the function CheckTableMetrics as well Commented Dec 15, 2015 at 12:38

1 Answer 1

4

Your problem is fairly simple:

$connection = $Db->real_connect($servername, $username, $password, $dbname, 3306);

This is wrong. real_connect() returns a boolean marking success or failure, not a connected database object. Instead, you should send $Db into your function, and it will all work.

Sign up to request clarification or add additional context in comments.

3 Comments

Well spotted - missed that completely
Great. It was so simple !
The simple problems are often the hardest to spot :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.