我似乎无法弄清楚为什么我的函数没有看到 $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/