0


I don't understand why i get this error, i can't understand what's wrong..

The Error: Fatal error: Uncaught Error: Call to a member function query() on null
This is the code:

/**
 * @category SQL Connection
 * @description Connect to SQL Database
 */
    $conn = new mysqli('server-0275.whmpanels.com', '---', '---', '---') or die(mysqli_error());

/**
 * @sub-category Functions
 * @description Main Functions
 */

    // If it's home
        if ($_SERVER['REQUEST_URI'] == '/' || $_SERVER['REQUEST_URI'] == '/index.php') {
        /**
         * @function Users
         * @description Count registered users
         */
            function users() {
                $rs = $conn->query("SELECT MAX(`id`) AS `maxUsers` FROM `vrp_users`");
                if ($row = mysqli_fetch_assoc($rs)) 
                    return $row['maxUsers'];
                return 0;
            }
Dharman
  • 30,962
  • 25
  • 85
  • 135
CodX
  • 3
  • 1
  • You have an error with `or die(mysqli_error())`. Please read: [Should we ever check for mysqli_connect() errors manually?](https://stackoverflow.com/q/58808332/1839439) – Dharman Dec 26 '19 at 13:43

1 Answers1

0

$conn is not accessible in the users() function as it was defined outside of the function. You can either access the global variable like this (not ideal - read up about why you shouldn't do this):

function users() {
    global $conn;
    $rs = $conn->query("SELECT MAX(`id`) AS `maxUsers` FROM `vrp_users`");
    //rest of code...
}

Or pass the $conn variable into the function

function users($conn) {
    $rs = $conn->query("SELECT MAX(`id`) AS `maxUsers` FROM `vrp_users`");
    //rest of code...
}
Leggy
  • 682
  • 7
  • 20