为什么可以';t我将一个连接变量传递给我的函数


Why can't I pass a connection variable to my function?

我似乎不明白为什么我的函数没有看到$conn变量。其他功能似乎运行良好。

这是一个文件,我在其中调用我的函数:

require_once('../functions.php');
if('POST' == htmlspecialchars($_SERVER['REQUEST_METHOD'])) {     
    $user_id = $_SESSION["user_id"];
    $day = $_POST["day"];
    $month = $_POST["month"];
    $year = $_POST["year"];
    $type = '';
    $content = $_POST["content"];
    add_bullet($user_id, $day, $month, $year, $type, $content, $conn);   
}

这是我的函数.pp

require_once('../include/db_connect.php');    
// other functions here..   
function add_bullet($user_id, $day, $month, $year, $type, $content, $conn) {    
    $sql = "INSERT INTO `mbt`.`bullets` (`id`, `user`, `day`, `month`, `year`, `type`, `content`) VALUES ('', '$user_id', '$day', '$month', '$year', '$type', '$content');";
    mysqli_query($conn, $sql);      
}

使用相同的方法,我的其他函数似乎也能正常工作。

这是我的db_connect.php

$dbserver = "xxx"; 
$dbuser = "xxx"; 
$dbpassword = "xxx"; 
$dbname = "xxx"; 
$conn = new mysqli($dbserver, $dbuser, $dbpassword, $dbname); 
if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); }

您不能只使用其他文件中需要的任何变量。。添加此全局设置,然后重试。。

$content = $_POST["content"];
global $conn;
add_bullet($user_id, $day, $month, $year, $type, $content, $conn);

一个更好的想法是在数据库文件中定义函数,它将返回连接,这样你就不需要传递它,只需要使用方法。。