View Full Version : database connection with mysqli

03-07-2013, 05:58 PM
I am trying to do an include for my db connection with mysqli but cannot not find any examples of how do to it.

This is what I have


function login()
$con = mysqli_connect('localhost', 'stuff', 'stuff', 'stuff');

// tried this as well $con = new mysqli(

So what is the extra step that I need to take? I know there is something missing in my function but everything I have tried does not work.

My db connection works directly in the page

This is the error I am getting

Fatal error: Call to a member function query() on a non-object in /home/content/51/10528751/html/login.php on line 49

Line 49 is


03-07-2013, 06:39 PM
What's the scope of the $mysqli->query call? Mysqli is (rightfully) not a global resource like mysql was. So you cannot do this:

function connect()
$mysqli = new Mysqli('localhost', 'user', 'password', 'db');


Since $mysqli doesn't exist outside the scope of connect.

03-07-2013, 07:11 PM
I see so the best thing is to keep it on the pages that need it?

I have many many queries calling it in a large variety of pages

03-07-2013, 08:02 PM
I don't understand what you are referring to about keeping it on the pages that need it.
What I'm referring to is that mysqli obeys the scope of code unlike the mysql library. So if you need to use it in functions you'll need to pass it in.

03-07-2013, 08:08 PM
I was just looking to move my db connection into an include file so when it gets changed I don't have to modify all the files just 1. Since its not a global resource as mysql it appears as though I need to keep the db connection on all the pages that require it to be there.

I don't know how to do it any other way, have looked but to no avail, hence this posting, to see if it is possible.

03-07-2013, 09:27 PM
The quickest solution is to define the database connection as global inside each of the functions tat needs to use if. For example:

function login()
global $mysqli;
$mysqli = mysqli_connect('localhost', 'stuff', 'stuff', 'stuff');

03-07-2013, 09:38 PM
Globalizing a variable can create horrific debugging.
But it's true, it is the easiest fix.

03-08-2013, 04:10 AM
I think what you are looking for is

Place it at the start of your PHP on each page that needs a connection.

Inside of somefile.php:

$connection = mysqli_connect('localhost','stuff','stuff','stuff');
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());