...

View Full Version : database connection with mysqli



harkly
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


include('library/login2.php');
login();


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

$result=$mysqli->query($sql);

Fou-Lu
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');
}

connect();
$mysqli->query('...');

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

harkly
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

Fou-Lu
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.

harkly
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.

felgall
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');
}

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

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


require_once('somefile.php');
Place it at the start of your PHP on each page that needs a connection.


Inside of somefile.php:


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



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum