Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community!

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial


Konrad Pilch
Konrad Pilch
2,435 Points



I know how OOP works, classes and stuff, i watched Hampton videos a lot aswell as on yt.

NOw , having in mind clean and reusable code , i made a login system but its messy , and it displays the name when i want to if its logged in.

Could somebody help me to chop this in the class? as well as to select e.g name, email whenever i want and output this to the user profile.

This is my loggin php:


// Check whether user has come from form

        echo "Please log in to continue";
        die("<br /><a href='index.php'>Log In </a>");

    //Assigning variables
    $username = $_POST['username'];
    $passwordAttempt = $_POST['password'];
    $hashPasswordAttempt = md5($passwordAttempt);

    //Check forminputs
    if($username == "" || $username == NULL){

        echo "Please enter a username";
        die("<br /><a href='index.php'>Go back </a>");


    if($passwordAttempt == "" || $passwordAttempt == NULL){

        echo "Please enter a passwordAttempt";
        die("<br /><a href='index.php'>Go back </a>");


    include ('libraries/database.php');

    $query = ("SELECT * FROM users WHERE username ='$username'");
    $result = mysqli_query($connect, $query);
    $hits = mysqli_affected_rows($connect);

    if($hits < 1){

        echo "Incorrect username and password combination";
        die("<br /><a href='index.php'>Go back </a>");


    while($row = mysqli_fetch_assoc($result)){

    $password = $row['password'];

    if($password != $hashPasswordAttempt){

        echo "Incorrect username and password combination";
        die("<br /><a href='index.php'>Go back </a>");


        // All check complete session starting
        $_SESSION['username'] = $username;





Ah right, i know, so many questions, ill go ahead and say that Steve Jobs told me to ask questions, so im asking :D

1 Answer

im not very advanced on OO php but I guess you could start by creating a class that will interface with your database, maybe a class for validation as well?

so when the user submits the form, it calls a validate class which will redirect to the login if validation fails, and call the login class if validation passes, then the login class will run the sql and will redirect to login if it fails or redirect to the appropriate page if its successful