El Anonimo
El Anonimo

Reputation: 1870

Query won't return true on successful execute()

MariaDB server version is 10.1.21.

Below is my Database class which is used in the User class to add users to the DB. The execute() method doesn't seem to return true when saving users to the DB though the users get added.

<?php

class Database {
    private $host = DB_HOST;
    private $user = DB_USER;
    private $pass = DB_PASS;
    private $dbname = DB_NAME;

    private $dbh;       // DB handler
    private $error;
    private $stmt;

    public function __construct() {
        // set DSN i. e. data source name
        $dsn = "mysql:host=".$this -> host.";dbname=".$this -> dbname;
        // set options
        $options = array(
            PDO::ATTR_PERSISTENT => true,
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
        );
        // create a new PDO instance
        try {
            $this -> dbh = new PDO($dsn, $this -> user, $this -> pass, $options);       // connector to DB
        } catch(PDOException $ex) {
            $this -> error = $ex -> getMessage();
        }
    }

    public function query($query) {
        $this -> stmt = $this -> dbh -> prepare($query);
    }

    public function bind($param, $value, $type = null) {
        if (is_null($type)) {
            switch (true) {
                case is_int($value):
                    $type = PDO::PARAM_INT;
                    break;
                case is_bool($value):
                    $type = PDO::PARAM_BOOL;
                    break;
                case is_null($value):
                    $type = PDO::PARAM_NULL;
                    break;
                default:
                    $type = PDO::PARAM_STR;
            }
        }
        $this -> stmt -> bindValue($param, $value, $type);
    }

    public function execute() {
        $this -> stmt -> execute();
    }

    public function resultset() {
        $this -> execute();
        return $this -> stmt -> fetchAll(PDO::FETCH_OBJ);       // FETCH_OBJ to fetch object from DB. Could be associative array
    }

    public function single() {
        $this -> execute();
        return $this -> stmt -> fetch(PDO::FETCH_OBJ);
    }

    public function rowCount() {
        return $this -> stmt -> rowCount();
    }

    public function lastInsertId() {
        return $this -> dbh -> lastInsertId();
    }

    public function beginTransaction() {
        return $this -> dbh -> beginTransaction();
    }

    public function endTransaction() {
        return $this -> dbh -> commit();
    }

    public function cancelTransaction() {
        return $this -> dbh -> rollback();
    }
}

The User class code is below. The execute() method in the public function register($data) doesn't seem to return true either on account only the false case gets executed in another code piece. Cutting the public function register($data) short with return true; just above if ($this -> db -> execute()) {...} allows to receive the success message.

<?php

class User {
    private $db;

    public function __construct() {
        $this -> db = new Database();
    }

    // register user
    public function register($data) {
        $this -> db -> query("INSERT INTO users (name, email, avatar, username, password, about, last_activity) VALUES (:name, :email, :avatar, :username, :password, :about, :last_activity)");
        $this -> db -> bind(':name', $data['name']);
        $this -> db -> bind(':email', $data['email']);
        $this -> db -> bind(':avatar', $data['avatar']);
        $this -> db -> bind(':username', $data['username']);
        $this -> db -> bind(':password', $data['password']);
        $this -> db -> bind(':about', $data['about']);
        $this -> db -> bind(':last_activity', $data['last_activity']);

        if ($this -> db -> execute()) {
            return true;
        } else {
            return false;
        }
    }

    // upload user avatar
    public function uploadAvatar() {
        $allowedExts = array("gif", "jpeg", "jpg", "png");
        $temp = explode(".", $_FILES['avatar']['name']);
        $extension = end($temp);

        if ((($_FILES['avatar']['type'] == "image/gif")
                || ($_FILES['avatar']['type'] == "image/jpeg")
                || ($_FILES['avatar']['type'] == "image/jpg")
                || ($_FILES['avatar']['type'] == "image/pjpeg")
                || ($_FILES['avatar']['type'] == "image/x-png")
                || ($_FILES['avatar']['type'] == "image/png"))
                && ($_FILES['avatar']['size'] < 50000)
                && in_array($extension, $allowedExts)) {
                    if ($_FILES['avatar']['error'] > 0) {
                        redirect('register.php', $_FILES['avatar']['error'], 'error');
                    } else {
                        if (file_exists('images/avatars/'.$_FILES['avatar']['name'])) {
                            redirect('register.php', "File already exists", 'error');
                        } else {
                            move_uploaded_file($_FILES['avatar']['tmp_name'], 'images/avatars/'.$_FILES['avatar']['name']);
                            return true;
                        }
                    }
        } else {
            redirect('register.php', "Invalid file type", 'error');
        }
    }

    // user log in
    public function login($username, $password) {
        $this -> db -> query("SELECT * FROM users WHERE username = :username AND password = :password");
        $this -> db -> bind(':username', $username);
        $this -> db -> bind(':password', $password);

        $row = $this -> db -> single();

        if ($this -> db -> rowCount() > 0) {
            $this -> setUserData($row);
            return true;
        } else {
            return false;
        }
    }

    // set user data
    public function setUserData($row) {
        $_SESSION['is_logged_in'] = true;
        $_SESSION['user_id'] = $row -> id;
        $_SESSION['username'] = $row -> username;
        $_SESSION['name'] = $row -> name;
    }

    // log user out
    public function logout() {
        unset($_SESSION['is_logged_in']);
        unset($_SESSION['user_id']);
        unset($_SESSION['username']);
        unset($_SESSION['name']);
        return true;
    }

    // get total number of users
    public function getTotalUsers() {
        $this -> db -> query("SELECT * FROM users");
        $this -> db -> resultset();
        return $this -> db -> rowCount();
    }
}

The false case above gets processed in another code piece:

if ($user -> register($data)) {
                    redirect('index.php', 'You are registered and can now log in', 'success');
                } else {
                    redirect('index.php', 'Something went wrong with the registration', 'error');
                }

The only message that gets received is the error one.

Please suggest. I couldn't see what was wrong with the code. The users get added fine.

Upvotes: 0

Views: 202

Answers (1)

Alexey Chuhrov
Alexey Chuhrov

Reputation: 1787

Your Database execute() method returns nothing. Which is NULL which is false. So add return statement:

public function execute() {
    return $this -> stmt -> execute();
}

Upvotes: 1

Related Questions