我有一个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
  在第13行的/Applications/MAMP/htdocs/blog/includes/functions.php中
  
  警告: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变量传递给您的函数或将其设置为全局变量。

例如:

function show_posts($connection, $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_posts($user_id) {
    global $connection;

    $posts = array();
    $sql = "SELECT body, stamp from posts where user_id = '$user_id' order by stamp desc";
    $result = mysqli_query($connection, $sql);
}

关于php - PHP函数和MySQL连接,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/20494526/

10-15 18:38
查看更多