php - 为什么我无法将连接变量传递给我的函数?

标签 php mysql database 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);   
}

这是我的functions.php

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

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

关于php - 为什么我无法将连接变量传递给我的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29515854/

相关文章:

php - Activerecord 时区格式不正确

mysql - 加入只显示一条记录

php - 使用带有对象的 php session 还是访问数据库更好?

database - 一个字段可以同时充当同一个表中的外键和主键吗?

javascript - 如何通过 jQuery 将多个复选框数据发送到 PHP

MySQL WHERE IN 结果乱序

php - 在 composer.json 中运行命令行命令

php - 使用 PHP PDO/MySQL 连接到数据库的安全方法?

PHPMailer 无法连接 ot 服务器

php 多行 preg_match_all