我有存储这样的数据库连接信息一个database.php中的文件:PHP函数和MySQL连接
<?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;
}
?>
我的问题是这样的:
注意:未定义的变量:在 /应用程序连接/ MAMP/htdocs中/博客/包括/上线的functions.php 13
警告:mysqli_query()预计参数1是mysqli的,NULL给出 在/Applications/MAMP/htdocs/blog/includes/functions.php上线13
警告:mysqli_fetch_array()预计上 线15
的users.php文件具有需要在/Applications/MAMP/htdocs/blog/includes/functions.php给定的参数1被mysqli_result, 空('includes/functions.php')和require('includes/database.php')。但不知何故值不是通过?。我究竟做错了什么?请帮助我。我希望这是有道理的。未定义变量的问题发生在每个函数3.
它是一个变量作用域问题,您在函数之外定义了$连接等,因此函数无法访问需要将连接变量传递给函数的连接,因此您可以使用它 – Dave
因此,我应该只移动functions.php中的database.php的内容? –
像函数show_users($连接){ – AdRock