在 PHP 中导入带有 MySQLi 函数的文件会中断调用页面

Importing a file with MySQLi functions in PHP breaks calling page

main.php

导入 config.php、clubsData.php 并调用 checkEnrollment() 时,我的数据库 $link 未定义。这会中断所有查询并输出警告,例如“mysqli_prepare() expects parameter 1 to be mysqli, null given...”

session_start();
require_once($_SERVER['DOCUMENT_ROOT']."/imports/config.php");
require_once($_SERVER['DOCUMENT_ROOT']."/imports/clubsData.php");
checkEnrollment($user_id, $clubid);

config.php

$DB_SERVER = getenv('DB_HOST');
$DB_USERNAME = getenv('DB_USER');
$DB_PASSWORD = getenv('DB_PASSWORD');
$DB_NAME = getenv('DB_NAME');

$link = mysqli_connect($DB_SERVER, $DB_USERNAME, $DB_PASSWORD, $DB_NAME);

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

clubsData.php

function checkEnrollment($user_id, $club_id) {
    $sql = "SELECT role FROM in_clubs WHERE user_id = ? AND club_id = ?";
    $stmt = mysqli_prepare($link, $sql);
    mysqli_stmt_bind_param($stmt, "ss", $param_user_id, $param_club_id);
    $param_user_id = $user_id;
    $param_club_id = $club_id;
    mysqli_stmt_execute($stmt);
    mysqli_stmt_store_result($stmt);
    mysqli_stmt_fetch($stmt);
    if(mysqli_stmt_num_rows($stmt) == 1){       
        return true;
    } else {
        return false;
    }
    mysqli_stmt_close($stmt);
}

为此,您需要将 $link 变量作为参数传递给函数,就像传递 $user_id、$club_id 一样参数.

像这样定义你的函数:

function checkEnrollment($user_id, $club_id, $link) {
$sql = "SELECT role FROM in_clubs WHERE user_id = ? AND club_id = ?";
$stmt = mysqli_prepare($link, $sql);
mysqli_stmt_bind_param($stmt, "ss", $param_user_id, $param_club_id);
$param_user_id = $user_id;
$param_club_id = $club_id;
mysqli_stmt_execute($stmt);
mysqli_stmt_store_result($stmt);
mysqli_stmt_fetch($stmt);
if(mysqli_stmt_num_rows($stmt) == 1){       
    return true;
} else {
    return false;
}
mysqli_stmt_close($stmt);
}

然后这样称呼它:

checkEnrollment($user_id, $clubid, $link);