Why is my database connection not working? Object-oriented PHP

Asked

Viewed 72 times

0

<?php 
<?php 
class getForm{ 
    public $nome; 
    public $email;
    public $tel; 
    public $query;
    public $conexao = null;
    public $usuario = "root";
    public $senha = "";
    public $banco = "testando";
    public $servidor = "localhost";

    public function getNome(){ 
        $this->nome = $_POST['nome']; 
    } 

    public function getEmail(){ 
        $this->email = $_POST['email']; 
    } 

    public function getTel(){ 
        $this->tel = $_POST['tel']; 
    } 
}
if (isset($_POST['submit']))  {

    echo "<span style='color:green;'>Enviado com sucesso!</span>";
    function setConexao(){
        $this->conexao = mysqli_connect($this->servidor, $this->usuario, $this->senha, $this->banco);
        if($this->conexao)
        {
            echo "DEU";
        }
        else {
            echo "Falha na conexao com o Banco de Dados!<br />";
            echo "Erro: " . mysql_error();
            die();
        }
    }
    function setusuario(){

        $query = mysqli_query($this->conexao, "INSERT INTO contato
        VALUES ('$this->nome','$this->tel','$this->email')");
        echo "conectado";

    }

}
?>
  • Which error message appears?

  • Actually no error message appears, simply does not connect, no message appears that was to appear (only that of Sent successfully!), nor the error q I put, so I wanted to know if there is something wrong.

  • Tries to encapsulate mysqli_connect in a Try catch and see if it catches any exceptions.

  • Function setConexate(){ Try { $this->connected = mysqli_connect($this->server, $this->user, $this->password, $this->bank); } catch( Exception $e ) { echo $e->getCode(); } }

  • Somebody help me Please, I have to do this to get my internship vacancy and I have to hand it over to my supervisor

  • @Rebeca the connection is within the function "setConexao()", where are you calling it? in your code, nothing happens because the function is not being called

  • and where and how I call her?

Show 2 more comments

1 answer

1

class getForm{ 
    public $nome; 
    public $email;
    public $tel; 
    public $query;
    public $conexao = null;
    public $usuario = "root";
    public $senha = "";
    public $banco = "testando";
    public $servidor = "localhost";

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

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

    public function getTel($tel){ 
        $this->tel = $tel;
    }

    public function setConexao(){
        $this->conexao = mysqli_connect($this->servidor, $this->usuario, $this->senha, $this->banco);
        if(!$this->conexao){
            echo "Falha na conexao com o Banco de Dados!<br />";
            echo "Erro: " . mysql_error();
            die();
        }
    }

    public function setUsuario(){       
        $query = mysqli_query($this->conexao, "INSERT INTO contato
        VALUES ('$this->nome','$this->tel','$this->email')");
        echo "conectado";

    }
}

First you have created a class and need to instantiate it, in your case operations will occur when there is form Ubmit, then we will perform operations within the if(isset($_POST['submit'])).

Connection functions and user definition can be part of the main class, do not need to be within the if(), so you can access these functions from any other part of the code where the class is instantiated.

if (isset($_POST['submit']))  {
    /*
        Aqui nós instanciamos a classe
    */

    $getForm = new getForm();

    /*
        Agora teremos acesso as funções da sua classe, assim poderemos verificar a existencia dos dados necessários para a utilização das mesmas
        Após verificar a existencia e o preenchimento dos campos, chamamos as funções da classe responsáveis por definirem as variáveis que serão inseridas no banco de dados
        OBS: Veja que aterei as funções para facilitar a verificação e tratamento das variáveis antes de enviá-las ao banco de dados, evitando SQL Injections e outros possiveis problemas
    */

    if((isset($_POST['nome'])) && (!empty($_POST['nome']))){
        // fazer tratamento das variáveis antes de enviá-las ao banco de dados
        $getForm->getNome($_POST['nome']);
    }
    if((isset($_POST['email'])) && (!empty($_POST['email']))){
        // fazer tratamento das variáveis antes de enviá-las ao banco de dados
        $getForm->getEmail($_POST['email']);
    }
    if((isset($_POST['tel'])) && (!empty($_POST['tel']))){
        // fazer tratamento das variáveis antes de enviá-las ao banco de dados
        $getForm->getTel($_POST['tel']);
    }

    /*
        Agora podemos chamar as funções de conexão e envio dos dados
    */

    $getForm->setConexao();
    $getForm->setUsuario();

    echo "<span style='color:green;'>Enviado com sucesso!</span>";    
}

Handling of PHP Forms

Function reference FILTER_INPUT()

Reference to examples of PHP Regular Expressions

I suggest reading the PHP documentation and research on the treatment of forms and variables

Browser other questions tagged

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