【发布时间】:2013-12-27 23:21:30
【问题描述】:
我有一个 database.php 文件,它存储数据库连接信息,如下所示:
<?php
// Database connectivity stuff
$host = "localhost"; // Hostname for the database. Usually localhost
$username = "root"; // Username used to connect to the database
$password = "root"; // Password for the username used to connect to the database
$database = "blog"; // The database used
// Connect to the database using mysqli_connect
$connection = mysqli_connect($host, $username, $password, $database);
// Check the connection for errors
if (mysqli_connect_errno($connection)) {
// Stop the whole page from loading if errors occur
die("<br />Could not connect to the database. Please check the settings and try again.") . mysqli_connect_error() . mysqli_connect_errno();
}
?>
还有一个functions.php文件,包含以下内容:
<?php
// Functions file for the system
function show_posts($user_id) {
$posts = array();
$sql = "SELECT body, stamp from posts where user_id = '$user_id' order by stamp desc";
$result = mysqli_query($connection, $sql);
}
function show_users() {
$users = array();
$sql = "SELECT id, username FROM users WHERE status = 'active' ORDER BY username";
$result = mysqli_query($connection, $sql);
while ($data = mysqli_fetch_array($result)) {
$users[$data->id] = $data->username;
}
return $users;
}
function following($user_id) {
$users = array();
$sql = "SELECT DISTINCT user_id FROM following WHERE follower_id = $user_id";
$result = mysqli_query($connection, $sql);
while ($data = mysqli_fetch_assoc($result)) {
array_push($users, $data->user_id);
}
return $users;
}
?>
这两个文件都在 /includes 文件夹中。我现在有一个 users.php 文件,我想在其中显示用户列表。这是我尝试这样做的代码:
<?php
$users = show_users();
foreach ($users as $key => $value) {
echo $key . " " . $value;
}
?>
我的问题是这样的:
注意:未定义的变量:连接在 /Applications/MAMP/htdocs/blog/includes/functions.php 第 13 行
警告:mysqli_query() 期望参数 1 为 mysqli,给定 null 在 /Applications/MAMP/htdocs/blog/includes/functions.php 第 13 行
警告:mysqli_fetch_array() 期望参数 1 为 mysqli_result, /Applications/MAMP/htdocs/blog/includes/functions.php 中给出的 null 第 15 行
users.php 文件有 require('includes/functions.php') 和 require('includes/database.php')。但不知何故,这些值没有通过?。我究竟做错了什么?请帮帮我。我希望这是有道理的。 3的每个函数都会出现未定义变量的问题。
【问题讨论】:
-
这是一个变量范围问题,您在函数之外定义 $connection 等,因此函数无法访问您需要将连接变量传递到函数中的连接,以便您可以使用它
-
所以我应该只是在functions.php中移动database.php的内容?
-
点赞函数 show_users($connection) {
-
不只是将 $connection 作为参数传入
function show_posts($connection,$user_id) {