Problems with PHP PDO

Asked

Viewed 72 times

3

Next, I have the following method in a class called UsuarioDAO.

 public function insertUser(PojoUser $user) {

    if ($stmt = Conn::con() != null) {

        $stmt = Conn::con()->prepare('INSERT INTO usuario (email, username, password, lastaccess, active, createdat, updatedat) VALUES (:email, :username, :password, :lastaccess, :active, :createdat, :udatedat)');

        $stmt->bindValue(":email", $user->getEmail(), PDO::PARAM_STR);
        $stmt->bindValue(":username", $user->getUsername(), PDO::PARAM_STR);
        $stmt->bindValue(":password", $user->getPassword(), PDO::PARAM_STR);
        $stmt->bindValue(":lastaccess", $user->getLastAccess(), PDO::PARAM_STR);
        $stmt->bindValue(":active", $user->getActive(), PDO::PARAM_INT);
        $stmt->bindValue(":createdat", $user->getCreatedAt(), PDO::PARAM_STR);
        $stmt->bindValue(":udatedat", $user->getUpdatedAt(), PDO::PARAM_STR);

        $stmt->execute();

    } else {
        echo "<p class='msg-error'> Desculpe! Erro ao estabelecer conexão. Tente novamente mais tarde.</p>";
    }
}

This class takes as parameter an object of PojoUser, follows the code of the class below:

<?php

class PojoUser {

    private $id;
    private $email;
    private $username;
    private $password;
    private $lastAccess;
    private $active;
    private $createdAt;
    private $updatedAt;

    public function getId() {
        return $this->id;
    }

    public function setId($id) {
        $this->id = $id;
    }

    public function getEmail() {
        return $this->email;
    }

    public function setEmail($email) {
        $this->email = $email;
    }

    public function getUsername() {
        return $this->username;
    }

    public function setUsername($username) {
        $this->username = $username;
    }

    public function getPassword() {
        return $this->password;
    }

    public function setPassword($senha) {
        $this->senha = $senha;
    }    

    public function getLastAccess() {
        return $this->lastAccess;
    }

    public function setLastAccess($lastAccess) {
        $this->lastAccess = $lastAccess;
    }

    public function getActive() {
        return $this->active;
    }

    public function setActive($active) {
        $this->active = $active;
    }

    public function getCreatedAt() {
        return $this->createdAt;
    }

    public function setCreatedAt($createdAt) {
        $this->createdAt = $createdAt;
    }

    public function getUpdatedAt() {
        return $this->createdAt;
    }

    public function setUpdatedAt($updatedAt) {
        $this->updatedAt = $updatedAt;
    }

}

?>

I call these two classes on the user registration page:

<?php

include_once('Register.class.php');
include_once('UserDao.class.php');
include_once('PojoUser.class.php');
if ($_POST) {

    $email = $_POST['user-email'];
    $password = $_POST['user-password'];
    $username = $_POST['user'];
    $conUserPassword = $_POST['conf-user-password'];

    /*$re = new Register();*/

    $user = new PojoUser();
    $userDAO = new UserDAO();
    $data = date('d/m/Y');


    if ($password == $conUserPassword) {

        if (!($userDAO->userExists($email))) {

            if ($userDAO->userNameAvaiable($username)) {

                $cryptoPassword = $userDAO->crypto($password);

                $user->setEmail($email);
                $user->setUsername($username);
                $user->setPassword($cryptoPassword);
                $user->setLastAccess($data);
                $user->setActive(0);
                $user->setCreatedAt($data);
                $user->setUpdatedAt($data);

                $userDAO->insertUser($user);



                //echo "<p class='msg-success'>Usuário Cadastrado com sucesso! Confirme seu email por favor.</p>";

            } else {
                echo "<p class='msg-error'>Desculpe, este nome de usuário não está mais disponível</p>";
            }

        } else {
            echo "<p class='msg-error'>Hey, parece que você já esteve por aqui, este email já está cadastrado em nosso sistema!</p>";
        }

    } else {

        echo "<p class='msg-error'>Verifique se você digitou as senhas corretamente!</p>";
    }

}

?>

My problem is that the user is never registered in the bank. Can anyone help me understand why this?

  • Any error is displayed?

  • No, no mistake at all.

2 answers

1


So the error was in the password Setter of my class PojoUser:

private $id;
private $email;
private $username;
private $password;
private $lastAccess;
private $active;
private $createdAt;
private $updatedAt;

public function setPassword($senha) {
    $this->password = $senha;
}  

public function getPassword() {
    return $this->password;
}

I wasn’t referencing the variable $password but a non-existent variable $senha, this made my password always go null for the insertion method, which did not allow the registration in the database, because my getter returned password.

0

Probably the error is on that line:

if ($stmt = Conn::con() != null) {

The expression above evaluates whether Conn::con() is not null, and the result is a value boolean which is assigned the variable $stmt. Take an example:

$foo = null;

$bar = ($foo != null); // False porque $foo NÃO é diferente de null
$baz = ($foo == null); // True porque $foo é igual a null

var_dump($bar, $baz);

The correct way is to first assign the $stmt the value of Conn::con() and then make the comparison:

if (($stmt = Conn::con()) != null) {

The reason for this is because precedence of operators, more details: Qual a diferença entre “&&” e “||” e “and” e “or” em PHP? Qual usar?

  • No, it’s not that. I made this modification, and it didn’t work the same way. But when I pass an array with all the getters of the object, as execute() parameter, it works. But I really wanted to understand why it doesn’t work that way.

  • @Gamen If that’s not it, try the following inside the if (...) { ..: var_dump($stmt);.

  • Object(Pdostatement)#4 (1) { ["queryString"]=&gt; string(120) "INSERT INTO usuario (email, username, password, lastaccess, active, createdat, updatedat) VALUES (?, ? , ? , ? , ? , ? , ? )" }

  • In what you suggested

  • @Gamen And in the way you were using not? something else, check if the data is coming correctly, example: echo $user->getEmail();.

  • No, the way I was using doesn’t work either. Yes, the data is coming perfect, I’ve tested this.

  • @Gamen No execute see what is returned: var_dump($stmt->execute());, false or true.

  • And look too: print_r($stmt->errorInfo());, if you prefer to make a try/catch..: try { // código de inserção } catch(PDOException $e) { echo $e->getMessage(); } may also show something.

  • 1

    Man, thank you so much. I didn’t realize the error until you suggested I use var_dump($stmt->execute();. The password was going null. The error is in the password Setter in the Pojouser class, I have not referenced the password variable. Qnd you had me test the data, the password variable was the only one I jumped kkkk But thanks, and sorry for the hassle.

  • @Gamen Was Not Business. : ) If you want to post this as an answer and accept it, you can help others with similar problems.

  • I’ll do that the/

Show 6 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.