PDO inserting null

0

I'm trying to create a simple user registration screen, but I'm having trouble performing insert . The method is executed but MySQL inserts null instead of form fields that I get through a foreach , can you tell me where I'm 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 fields of the form through the foreach to pass to the method Insert

<?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   


?>
    
asked by anonymous 20.03.2017 / 20:15

1 answer

2

There are some strange things in this code, the main problem is not the $user object, 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 two arguments are passed in the call.

Statement:

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

Call:

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

The idea of set methods is to just assign an (external) value to an (internal) property of the object, it does not make much sense for it to have a return saved in exe - cutions.

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

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

Class Usuario_crud{
    public static $conexaoPDO;

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

//demais códigos
    
20.03.2017 / 20:42