Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I've just started to look into Mysqli and I've understood most of it now, but I'm having a problem with a function that connects me to the database on other pages.

What I'm aiming to have is to just type getConnected(); where i need to connect.

this is the code:

function getConnected() {
$host = 'localhost';
$user = 'logintest';
$pass = 'logintest';
$db = 'vibo';

$mysqli = new mysqli($host, $user, $pass, $db);

if($mysqli->connect_error) {
    die('Connect Error (' . mysqli_connect_errno() . ') '
            . mysqli_connect_error());
}
}

and this is the error i get:

Notice: Undefined variable: mysqli in C:\xampp\htdocs\xampp\loginsystem\index.php on line 19
share|improve this question
if you set a var in a function, you cant' use that out – Sam Mar 5 at 14:16
Sam is correct, look up php variable scope. You may be able to return the variable with the line: return $mysqli; And then call the function like so: $con = getConnected(); – Keeleon Mar 5 at 14:17
Where are you using this function? Need a bit more of it – asprin Mar 5 at 14:17
ah, so i need global variables? – Jake Snake Mar 5 at 14:17
@user2021893: No, just return the variable as Keeleon says. – Marcel Korpel Mar 5 at 14:20
show 1 more comment

closed as not a real question by George Stocker Mar 8 at 14:13

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.If this question can be reworded to fit the rules in the help center, please edit the question.

1 Answer

up vote 2 down vote accepted

As some users have suggested (and is the best way), return the mysqli instance

function getConnected($host,$user,$pass,$db) {

   $mysqli = new mysqli($host, $user, $pass, $db);

   if($mysqli->connect_error) 
     die('Connect Error (' . mysqli_connect_errno() . ') '. mysqli_connect_error());

   return $mysqli;
}

Example:

$mysqli = getConnected('localhost','user','password','database');
share|improve this answer
Thank you and everyone else! This is the solution. – Jake Snake Mar 5 at 14:30

Not the answer you're looking for? Browse other questions tagged or ask your own question.