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?

Datacrawler
  • 2,472
  • 5
  • 38
  • 81

1 Answers1

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.

TwoStraws
  • 11,965
  • 3
  • 52
  • 69