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! While you're at it, check out some resources Treehouse students have shared here.

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

PHP

Konrad Pilch
Konrad Pilch
2,435 Points

PHP Use Object

HI,

Could somebody tell me on how could i make a User object or class in order that each have their own account? meaning how can i make so when somebody register, i put them into a template that i probably pull them with id so its unique .

Meaning if i make a class user

class User {

    $name =>
    $age =>

}

? or how ? : p i looked at a lot of fortums , tutorials etc.. even here but im still now sure how to do it.

2 Answers

Justin Horner
STAFF
Justin Horner
Treehouse Guest Teacher

Hello Konrad,

So your question is how should you create a PHP class around the concept of users for your application. Without knowing you data access story, let's say we were to create a simple User domain model that stores a few properties and has a static sign in method that will return a User instance if sign in in successfully, or null if the sign in attempt fails. It might look something like this.

<?php  

class User {
    public $user_id;
    public $user_name;
    public $last_name;
    public $first_name;
    public $date_of_birth;

    static public function sign_in($userName, $password) {

        // Attempt sign in. If successful, return a new User instance, otherwise return NULL
        if($userName == "jdoe" && $password == "pw123") {
            $user = new User();
            $user->user_id = 1;
            $user->first_name = "John";
            $user->last_name = "Doe";
            $user->user_name = "jdoe";

            return $user;
        } else {
            return NULL;
        }
    }

    public function get_full_name() {
        return $this->first_name . " " . $this->last_name . " (" . $this->user_name . ")";
    }
}


$user = User::sign_in("jdoe", "pw123");

if($user === NULL) {
    echo "Authentication failed. Try again";
} else {
    echo $user->get_full_name();
}

?>

Obviously, your sign in method should tie-in with your back-end and set the properties of the new User object accordingly, but this is just an example. Of course, In a real world scenario you would use some type of cryptography for the password. You would be comparing a hash, not the actual password as I have done for illustration purposes.

I hope this helps.

Konrad Pilch
Konrad Pilch
2,435 Points

Hello Justin,

Thank you very for your response. I think thats what i meant , i mean class User yes.

What im trying to do is im learning how to log in user and have its own account , unique. Its kinda hard , every tutorial i look is outdated .

I see it here and i can pretty understand it and hopefuly, maybe try to work on it , i hope : p

Do you maybe know any tutorials, or books or something that could teach me how to make a login ? meaning like treehouse. we log in , and each of us has its own accaount and can post on forum etc..

Thank you really much for this.

Justin Horner
Justin Horner
Treehouse Guest Teacher

You're welcome! I'm glad to help. Take a look at this tutorial that walks through the process of creating an authentication system with PHP and MySQL.

It is dated, but the concepts should be sound.

Konrad Pilch
Konrad Pilch
2,435 Points

I found something very useful here that explains how this wokrs what you just put , the code :)

Maybe sm1 will find this in google so he will have a full guide to do what i wanted xd and overall, i think the article is great and thank yo uvery much for this piece of code, i will look and try to learn about it now :)

Konrad Pilch
Konrad Pilch
2,435 Points

xd one question again , xd could you tell me whats code is in the sign_in and full_name class?

Konrad Pilch
Konrad Pilch
2,435 Points

Or wait, sign in is the name of the function right : p as i understood so when the person tries to sign in, i put the code in () and then it will execute the code in the sing in below

Konrad Pilch
Konrad Pilch
2,435 Points

If i want to transform this :

login.php

``php

<?php ini_set('display_errors','On'); ini_set('error_reporting',E_ALL|E_STRICT);

SESSION_START(); date_default_timezone_set('UTC'); // Check whether user has come from form if(!isset($_POST['submit'])){

    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>");

}else{

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

    header("location:user.php");

    die("");

}

}

user.php


```php

<?php

SESSION_START();

if(!isset($_SESSION['username'])){

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

}

$username = $_SESSION['username'];

?>
<?php include 'template/includes/header.php' ?>

<!-- User Profile -->
<div class="container">




    <li class="topic">
        <div class="row">
            <div class="col-md-3">
                <img class="product-avatar pull-left" src="img/imgSlide3.jpg" />
                <?php echo "Name: <strong> $username </strong> ."; ?><br>
                <?php echo "Surname: <strong> $username </strong> ."; ?><br>
                <?php echo "Password: <strong> $username </strong> ."; ?><br>
                <?php echo "DoB: <strong> $username </strong> ."; ?><br>
            </div><!-- /col-md-3 -->
            <div class="col-md-9">
                <div class="topic-content pull-right">
                    <h3><a href="">Buy Sell Earn Invest</a></h3>
                    <div class="topic-info">
                        <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
                        tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
                        quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
                        consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
                        cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
                        proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
                    </div>
                </div><!-- /topic-content -->
            </div><!-- /col-md-0 -->
        </div><!-- /row -->
    </li><!-- /topics -->

</div><!-- /container -->

With a database of this :

user_email
user_password
user_firstname
user_lastname
user_id
user_avatar
user_shortbio
user_username
user_dob
user_gender
user_joindate

And acces the data to the user page , template whenever i can ? : p

HOw could i make it in OOP? i made it in this form working, but thats the wrong way in this modern days i believe.