使用来自不同文件的函数时,mysqli数据库连接错误 [英] mysqli database connection error when using functions from different files

查看:52
本文介绍了使用来自不同文件的函数时,mysqli数据库连接错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个问题,就是我未从其他文件包含的函数打开或使用mysqli-connection.在下面查看设置.如果我将所有代码都放在一个文件中,则可以完美运行,但是以这种方式不会发生任何事情.

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);
?>

推荐答案

此问题通过更改文件functions.php来解决:

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 ;)

这篇关于使用来自不同文件的函数时,mysqli数据库连接错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆