I'm in the basics of learning to code in OOP. So far I've tried simple input/output and succeeded but am now trying to move onto something still rather basic but a step up from previous attempts.

Anyway, I'm writing a login script connecting to a PDO database. I've tested all input/outputs which work fine, but the actual selecting the user info from the database just doesn't work. I'm getting this error:
Fatal error: Call to undefined function getUser() in C:\xampp\htdocs\classes\loginclass.php on line 25

If I'm going about this the wrong way, please let me know as I'm just testing out more efficient ways of coding which is why I'm going for OOP rather than procedural.

index.php

<form method = "post" action="login.php">
   <label>Username</label><input type="text" name="username" id="username"><br />
   <label>Password</label><input type="password" name="password">
   <label>Password</label><input type="password" name="password2">
    <input type="submit" value="submit" name="submit">
</form>

login.php

<?php

//Get data from the form
if (isset($_POST['submit'])){
    $username = $_POST['username'];
    $password = $_POST['password'];
    $password2 = $_POST['password2'];
}

//Include the class files
include "classes/loginclass.php";

//Instantiate the login function
$login = new Login();

//Set the password variables in the class to match the password passed from the form
$login->password = $password;
$login->password2 = $password2;

//Do it!
$login->logMeIn();
?>

loginclass.php

<?php


class Login {

    //Declare variables
    public $username;
    public $password;
    public $password2;
    //Start login function
    function logMeIn(){

        //Check if passwords match
        if ($this->password == $this->password2){ //Passwords match, now include db.php and check if connection to database is successful
            include ("classes/db.php");
            if ($success = true){
                //echo "Connected to db via PDO...";
                include ("classes/userclass.php");
                $user = new getUser();
                $user->table = "users";
                $user->username = $username;
                $user->where = "username";

                //Do it!
                getUserDetails();
            }else {
                die("Not connected to the database");
            }
        }else {
            die("Your passwords do not match");
        }
    }
}

?>

db.php

<?php

error_reporting(E_ALL);
ini_set('display_errors','1');

$username = "***";
$password = "***";
$id = 1;

try {
    $conn = new PDO('mysql:host=localhost;dbname=user', $username, $password);
    $success = true;
} catch(PDOException $e) {
    echo 'ERROR: ' . $e->getMessage();
}

?>

userclass.php

<?php



class getUser {

    //Declare variables
    public $username;

    //Get user details from database
    function getUserDetails(){
        include ("classes/db.php");
        $stmt = $conn->prepare('SELECT * FROM $this->table WHERE $this->where = :$this->$username');
        $stmt->execute(array('username' => $username));
        while($row = $stmt->fetch()) {
            print_r($row);
        }

    }


}

?>

Thanks in advance for any help/advise you give me.

getUserDetails(); should be $user->getUserDetails(); since it's a method of the getUser class.

The getUser class will need some more work. The query as it is now will fail.

Additionally, I don't think the getUser class should be a class. All it does is execute a query, which is the basic functionality of PDO. Furthermore, using the global $conn is anti-OO. The OO way would be to pass the PDO object as a parameter to the constructor of the login class, so it can be stored and used.

Thanks for your advise. The getUser class only has one function in it at the moment, but as the script progresses, it will store all user functions so would this still be appropriate as a class if I'm using it to get user info, update user info, delete user info?

As for the constructor, is this the __construct function? Sorry, I'm totally novice. The actual PDO script is something I found online here: http://net.tutsplus.com/tutorials/php/php-database-access-are-you-doing-it-correctly/ ironically the post is titled "are you doing it correctly"

I did what you recommended which was $user->getUserDetails(); but while there are no errors displaying, there is nothing at all displaying. I think the problem is that it is not finding the user details in the database using the $this commands. I tried to echo in the while loop and nothing outputted so I changed the select code to:

    //Declare variables
    public $username;
    $username = "scott";
    //Get user details from database
    function getUserDetails(){
        include ("classes/db.php");
        $stmt = $conn->prepare('SELECT * FROM users WHERE username = :$username');
        $stmt->execute(array('username' => $username));
        while($row = $stmt->fetch()) {
            echo "boo";
            print_r($row);
        }

This outputs the following error:

Parse error: syntax error, unexpected '$username' (T_VARIABLE), expecting function (T_FUNCTION)

I am not sure, but can you try that query withou colon (:). I mean remove colon from begning of $username in query string.

$stmt = $conn->prepare("SELECT * FROM users WHERE username = $username");
Member Avatar for diafol

Nice PDO wrapper here: http://code.google.com/p/php-pdo-wrapper-class/

Try:

$stmt = $conn->prepare('SELECT * FROM users WHERE username = :username');
$stmt->execute(array(':username' => $username));

The getUser class only has one function in it at the moment, but as the script progresses, it will store all user functions so would this still be appropriate as a class if I'm using it to get user info, update user info, delete user info?

If you make the class represent an actual user than I agree it has a purpose. IMHO you should pass the username and passwords to the constructor (__construct()), which will then load all other details from the database. You can pass the PDO object as a parameter too. In this situation it will be the Login class that will lose it's purpose.

Ok so I've taken out the colon and it still didn't work so I changed:

    $stmt = $conn->prepare('SELECT * FROM users WHERE username = :$username');

To:

    $stmt = $conn->prepare('SELECT * FROM users WHERE username = "scott"');

And I get the expected output: booArray ( [id] => 1 [0] => 1 [username] => scott [1] => scott [password] => statue [2] => statue ) booArray ( [id] => 1 [0] => 1 [username] => scott [1] => scott [password] => statue [2] => password )

Now upon further inspection, it appears that $this->username is outputting the username from the db file which is 'root' rather than the username required which is 'scott'

From this, I changed the variable $username to $usernameb to prevent a clash but get the following error:

Notice: Undefined variable: usernameb in C:\xampp\htdocs\classes\userclass.php on line 18
root
Notice: Undefined variable: usernameb in C:\xampp\htdocs\classes\userclass.php on line 18

Changed files:

userclass.php

<?php



class getUserDetails {

    //Declare variables
    public $username;
    public $usernameb;

    //Get user details from database
    function getUserDetails(){

        include ("classes/db.php");

        echo $this->usernameb;
        $stmt = $conn->prepare('SELECT * FROM users WHERE username = "$this->usernameb"');
        $stmt->execute(array('username' => $usernameb));
        while($row = $stmt->fetch()) {
            print_r($row);
        }

    }


}

?>

loginclass.php

<?php


class Login {

    //Declare variables
    public $usernameb;
    public $password;
    public $password2;
    //Start login function
    function logMeIn(){

        //Check if passwords match
        if ($this->password == $this->password2){ //Passwords match, now include db.php and check if connection to database is successful
            include ("classes/db.php");
            if ($success = true){

                //echo "Connected to db via PDO...";
                include ("classes/userclass.php");
                $user = new getUserDetails();
                $user->table = "users";
                $user->usernameb = $username;
                $user->where = "username";

                //Do it!
                $user->getUserDetails();

            }else {
                die("Not connected to the database");
            }
        }else {
            die("Your passwords do not match");
        }
    }
}

?>

'SELECT * FROM users WHERE username = :$username'

This doesn't work, because single quoted strings don't do variable substitution. See the last post from diafol or utrivedi.

Thanks for your help everyone. It is now working.

Member Avatar for diafol

OK, mark as solved, if it is.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.