Search code examples
phparraysmysqlisystemranking

Ranking system using mysqli


I want to check if the user what rank a user has, which is stored in my database as an integer of 0, 1, 2, or 3.

I want it to be echo'd like echo $my_rank; #Instead of it saying 0,1,2,or 3 it says User for 0, Moderator for 1, Admin for 2, and Owner for 3.

Here is my code:

$my_rank = $_SESSION['rank'] = array("owner","administrator","moderator","user");

$rank = array (
    '0' => 'user',
    '1' => 'moderator',
    '2' => 'administrator',
    '3' => 'owner'
);

config.php

<?php

# Error Reporting
error_reporting(E_ERROR | E_WARNING | E_PARSE | E_NOTICE);

# No Error Reporting
//error_reporting(0);

# Message Responses
$success = array();
$danger = array();
$warning = array();
$info = array();

# Define the Database
define('DB_SERVER','localhost');
define('DB_USERNAME','blah');
define('DB_PASSWORD','blah');
define('DB_DATABASE','blah');

# Connect to the database
$con = mysqli_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_DATABASE);
if (!$con) {
    $danger[] = mysqli_connect_error();
} else {
    //echo "It worked";
}
?>

Solution

  • One can query the database with sql statements. The one you're looking for is a select upon the usertable:

    // array which holds the info
    $rank = array ('user', 'moderator', 'administrator', 'owner');
    // set up db connection
    $con = mysqli_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_DATABASE);
    if (!$con) {
        $danger[] = mysqli_connect_error();
    } else { 
        //echo "It worked";
    
        // Baklap4's Addition:
    
        // SQL statement to retrieve the row where username is piet
        $sql = "SELECT * FROM Users WHERE username = `piet`";
    
        // Execute the query and check if there is a result.
        if ($result = $con->query($sql)) { 
            // if there are results loop through them.
            while ($row = mysqli_fetch_assoc($result)) {
                // print for each rank a different rank name.
                echo $rank[$row['rank']];
            } 
            // free resultset
            $result->close();
        } 
        // close connection
        $con->close();
        //clean up the temp variables 
        unset($obj); 
        unset($sql); 
        unset($result);
    }
    

    This will retrieve The user Piet from your database and print the rank (which is listed in the database). Then it'll unset all the temporary values made within the whileloop so you can't reuse them again.

    What you should do is change the hard coded value piet to a variable. One could go to http://localhost/scriptname.php?username=piet to retrieve the same outcome.

    To make this a variable change the sql line as following:

    $sql = "SELECT * FROM Users WHERE username = $_GET['username']";