PDO inserting null

Asked

Viewed 304 times

0

I’m trying to create a simple screen of user registration, but I’m having problems performing the insert. The method is executed but the MySQL inserts null instead of form fields I get through a foreach, can you tell me where I’m going wrong?

I’m using PDO Connection.

Usuario.php

<?php
    Class Usuario{

    private $id_login;
    private $usuario;
    private $senha;
    private $status;
    private $nome;
    private $sobrenome;


    public function __construct(){ 

        // 
    } 

    public function getId_login(){
    return $this->id_login;

    }

    public function setId_login($id_login){
    return $this->id_login = $id_login;

    }

    public function getUsuario(){
    return $this->usuario;

    }

    public function setUsuario($usuario){
    return $this->usuario = $usuario;

    }

    public function getSenha(){
    return $this->senha;

    }

    public function setSenha($senha){
    return $this->senha = $senha;

    }

    public function getStatus(){
    return $this->status;

    }

    public function setStatus($status){
    return $this->status = $status;

    }

    public function getNome(){
    return $this->nome;
    }

    public function setNome($nome){  
    return $this->nome = $nome;

    }
    public function getSobrenome(){
    return $this->sobrenome;
    }

    public function setSobrenome($sobrenome){  
    return $this->sobrenome = $sobrenome;}


} // fim da classe usuario

?>

usuario_crud.php

<?php

        Class Usuario_crud{

        public static $conexaoPDO;

        // Instanciando a conexao  e a classe
        public function __construct(){

        $this->conexaopdo = Conexao::getConexao();


     } public function Inserir(Usuario $usuario){

        try{ 

            // variavel recebendo a consulta

            $insert = "INSERT INTO tbl_login_admin (
                        usuario,
                        senha,
                        nome,
                        sobrenome)
                        VALUES(
                        :usuario,
                        :senha,
                        :nome,
                        :sobrenome)";

                        // abrindo a classe de conexão PDO

                        $prepare_sql = $this->conexaopdo->prepare($insert);

                        // repassando parametros através de bindParam
                        $prepare_sql->bindValue(":usuario", $usuario->getUsuario());
                        $prepare_sql->bindValue(":senha", $usuario->getSenha());
                        $prepare_sql->bindValue(":nome", $usuario->getNome());
                        $prepare_sql->bindValue(":sobrenome", $usuario->getSobrenome());

                        // executando a instrução
                         return $prepare_sql->execute();    


            } // fim do try

            catch (Exception $e) {
                Echo " $e Ocorreu um erro ao tentar executar essa Inclusão de Dados, Tente novamente mais tarde
                ou contato o administrador do Sistema";

             }

            } // fim da function Insert

?>

// here and where I go through the form fields through the foreach to pass to the Insert method

<?php

      if (isset($_POST['cadastrar'])){

            //laço que percorre os campos para obter os dados digitados no HTML através da Funçao $_POST
            foreach ($_POST as $campo => $valor) {
            $$campo = post($campo);
           }

              // instanciando a classe usuario.
              $user = new Usuario();

              // instanciando a classe usuario crud
              $user_crud = new Usuario_crud();


              // iniciando o metodo de Inserir
              $user_crud->inserir($user, $campo);



      } // fim do if   


?>
  • 1

    you saw that $$campo = post($campo); has 2 $?

  • 1

    Nowhere did you set the properties of the object $user. Nor does a method make much sense set() return value. public static $conexaoPDO; doesn’t seem to be used for anything in the code.

  • Hello friend, answering your question, I did see that the variable $$field has 2 $$ .. so actually as it is in the loop so it automatically gets the name fields of html, if you look at the foreach then I have a function that removes the '' from the field.. about the part of the connectionp is it q starts, if I take that chunk of the code Insert does not work. thanks for the help.. guys! now ok

1 answer

2


There are some strange things in these codes, the main problem is not popular the object $user, the calls of set() must have some value that comes from the form in the example I used fixed values.

$user_crud = new Usuario_crud();

$user = new Usuario();
$user->setUsuario('fulano');
$user->setSenha('123');
$user->setNome('fulano da silva');
//demais sets ...

$user_crud->inserir($user);

Note that in the signature the insert method defines only one parameter and in the call two arguments are passed.

Statement:

Class Usuario_crud{
   //código omitideo 
   public function Inserir(Usuario $usuario){

Calling for:

$user_crud->inserir($user, $campo); //esse $campo não deve estar aí

The idea of set methods is just to assign an (external) value to an (internal) property of the object it doesn’t make much sense to have a saved Return in exceptions.

public function setStatus($status){
   return $this->status = $status;
}

What is the purpose of $conexaoPDO? A subtle detail is in the costrutor a proprieade (conexaopdo) is created dynamically which means if the Constutor fails or ceases to be used it will never exist soon your connection will fail, in which case it is best to define this property in the class body.

Class Usuario_crud{
    public static $conexaoPDO;

    public function __construct(){
      $this->conexaopdo = Conexao::getConexao();
    }

//demais códigos
  • even with this, I believe that not much will help. the ideal would be to stop using the PDO with classes, and simply use the mysqli and functions.

  • thanks friend! was that same the problem was not passing the parameter to the object ai was not saving in the bank! (I was catching rs.. I am new in php) now it worked. About the connection Pdo I have a connection class and I call her there (I had not posted her here..) if I take her out of _Construct then I get error while doing the Insert, but I will follow her tip and put her in the body of the class, thank you very much for the help! complementing, if you find it necessary I put the class here of connection thanks

Browser other questions tagged

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