Johnny
Johnny

Reputation: 63

PHP MySQL Admin Level

This is my user table

CREATE TABLE `users` (
  `id` INT(11) NOT NULL AUTO_INCREMENT,
  `firstname` VARCHAR(255) NOT NULL,
  `lastname` VARCHAR(255) NOT NULL,
  `email` VARCHAR(255) NOT NULL,
  `username` VARCHAR(255) NOT NULL,
  `password` VARCHAR(100) NOT NULL,
  `level` ENUM('0','1') NOT NULL DEFAULT '0',
  PRIMARY KEY (`id`)

So lets say I am on index.php

I want that if user level = 1, then he can see a link appear on the page. Other wise if level = 0, he will never see that link.

How can I do that?

Upvotes: 0

Views: 523

Answers (4)

Leandro Papasidero
Leandro Papasidero

Reputation: 3738

<?php
try {
    $dbh = new PDO("mysql:host=localhost;dbname=dbName", 'dbUser', 'dbPassword');

    //Check username and password
    /*** The SQL SELECT statement ***/
    $sth = $dbh->prepare("SELECT level FROM user WHERE username = ? and password = ?");
    $sth->execute(array('[email protected]', '2222')); // these values are passed via SESSION, POST, etc
                                                     //make sure to encrypt password
    $user = $sth->fetch(PDO::FETCH_ASSOC);

    if(!empty($user) && $user['level'] == 1) {
        echo "link";
    }  else {
        echo "no-link";
    }

    /*** close the database connection ***/
    $dbh = null;
} catch (PDOException $e) {
    echo $e->getMessage();
}

Upvotes: 0

ryvasquez
ryvasquez

Reputation: 158

I think you want something like this.

in your login module do something like this

session_start();
$_SESSION['level'] = 1; // passed the level from you database.

and in your pages.

session_start();
if (isset($_SESSION['level']) && (int) $_SESSION['level'] === 1) {
    echo '<a>Link for admin</a>';
}

Upvotes: 1

Josh
Josh

Reputation: 949

You could use $_SESSION. So for example when your user logs in, you can set the session variable for level such as:

When your user logs in:

session_start(); // You must use this at the beginning of every page you use $_SESSION on
// Query here to select your user
$mysqli = new mysqli(HOST_NAME, DB_USER, DB_PASSWORD, DB_NAME);
//$username is the username of the user who is logging in.
$sql = "SELECT * FROM users WHERE username = '$username'";
$mysqli->query($sql);

if ($result && $result->num_rows > 0)
{
    while ($row = $result->fetch_assoc())
    {
        $_SESSION['level'] = $row['level'];
    }
}

On your index.php page (or any other page you want to check the user level):

session_start(); // This is reqd once on any page you use $_SESSION
// Then on your page you can use 
if (!empty($_SESSION['level']) && $_SESSION['level'] == 1)
{
    echo '<a href="">Your Link</a>';
}

Upvotes: 0

Kyle Coventry
Kyle Coventry

Reputation: 555

You should use session codes. Set a session code value to the value of level, and depending on that value display the link or not.

Upvotes: 0

Related Questions