php - DB connection issues while converting mysql to mysqli
Ok so Im working to update my website to mysqli and I am having a difficulty with DB.php include for the db connection.
So my db.php looks like this.
<?php
$username="usern";
$server="server";
$password="pwd";
$database="db";
//MySQLi methods
$mysqli = new mysqli($server, $username, $password, $database) or trigger_error ( mysqli_connect_errno().mysqli_connect_error() );
?>
Note: the sql error output is for debugging Im aware that outputting sql and verbose errors is not good practice ;)
Anyways, so that works just fine.
After updating the db.php file to mysqli im having issues with all the pages that use that. Basically even with the include I get the following errors mysqli in \display_functions.php on line 21 Fatal error: Call to a member function query() on a non-object in r\includes\display_functions.php on line 21
The relevant portion of that file is:
function showConfig ($configID)
{
date_default_timezone_set('America/Denver');
require_once($_SERVER["DOCUMENT_ROOT"] . "/includes/DB.php");
$tbl_name="avr";
// Get information from DB for display
$configQuery="SELECT * FROM $tbl_name WHERE configID=$configID";
$configResult=$mysqli->query($configQuery);
<some more code>
}
When this was all mysql it worked and now it doesnt and Im not really sure why. I thought the include statement was supposed to bring in everything from the noted file but the only way to make this function (and others like it) work is by basically putting the contents of DB.php inside the function. Which is of course a terrible practice.
Also, still kind of learning all of this so forgive this ignorant question but it only became a problem with the time zone change this weekend, how would i setup the default timezone function so I dont have to put it in everything?
Answer
Solution:
the $mysqli inside the function has local scope. it's not the same variable. you need to either pass $mysqli as a parameter
or use a global declaration inside the function