mysqli database connection error when using functions from different files

筅森魡賤 提交于 2020-01-07 05:34:08

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!