问题
I have a problem with the mysqli-connection not being open or used by functions which I include from other files. Look below at the setup. If I take all the code into one file, it works perfectly but in this way, nothing happens.
connection.php
<?php
function connect() {
$db = new mysqli("host", "user", "pswrd", "database");
return $db;
}
?>
functions.php
<?php
function get_user_email($user_id) {
$sql = "SELECT email FROM user_acc WHERE user_id='$user_id'";
if(!$result = $db->query($sql)) {die("woops!");}
$data = $result->fetch_assoc();
return $data['email'];
}
?>
index.php
<?php
include("connection.php");
include("functions.php");
$db = connect();
echo get_user_email(1);
?>
回答1:
This was solved by changing the file functions.php:
<?php
function get_user_email($user_id) {
global $db; //This is what was needed!
$sql = "SELECT email FROM user_acc WHERE user_id='$user_id'";
if(!$result = $db->query($sql)) {die("woops!");}
$data = $result->fetch_assoc();
return $data['email'];
}
?>
Thank you Your Common Sense for supplying the indirect answer that lead to answering this uestion ;)
来源:https://stackoverflow.com/questions/16498855/mysqli-database-connection-error-when-using-functions-from-different-files