3
\$\begingroup\$

I'm trying to create my user.class.php constructor but I don't know really much about POO so I'm going to tell you what I'm doing and I hope you could help me.

user.class.php

class user {
    private $fullname;
    private $age;
    private $email;
    private $sex;
    private $nacionality;

        public function __construct($usrId){
            $mysqli = new connection_mysqli(); // I've already implemented this and it works.
            $query = "SELECT * FROM USERS WHERE USER_ID = $userId";
            if ($result = $mysqli->query($query)) {
               $userData = $result->fetch_assoc(); 
               $this->fullname = $userData['fullname'];
               $this->age = $userData['age'];
               $this->email = $userData['email'];
               //.....
            }
        parent::__construct($usrId);

    }
}

What I'm going to do on my index.php is this:

index.php

<?php
include('scripts/class/user.class.php');
$user = new user($_SESSION['userid'];
echo $user->fullname;
?>

So, is this going to work right? Is this well-programmed? Any tips?

\$\endgroup\$
1
  • \$\begingroup\$ All your instance vars are private, this will not work. echo $user->fullname; \$\endgroup\$
    – bumperbox
    Commented Nov 11, 2014 at 2:54

2 Answers 2

4
\$\begingroup\$

First of all I recommend you to setup a local webserver to test your php code, if you have not done so jet (I assume you haven't tried your code, since your asking if it's going to work).

Secondly you should abandon mysqli for PDO. Read PHP Database Access: Are You Doing It Correctly?

Also, why are you calling the parent's constructor when the user class has no parent (eg. the class does not extend another class)?

\$\endgroup\$
2
\$\begingroup\$

I just have a couple of small points:

  • class names should be uppercase,
  • when writing SQL queries, use uppercase either for keywords, or for names, but not both (it's easier to read that way).
  • don't use select *, but only select what you actually need.
  • nationality is misspelled.
  • you control the session, but who knows how the id actually got there. I would always use prepared statements with non-constant data (or at least escape the data) to avoid SQL injection.
  • your indentation is slightly off.
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.