Script "most beautiful"

-2

I am using the following code for the class User:

<?php
    class Usuario {
        public $nome, $email;
        private $senha;
        private $mysqli;

        public function __construct($nome, $email, $senha){
            $this->nome = $nome;
            $this->email = $email;
            $this->senha = $senha;
            $this->conectar();
            $this->validarUsuario();
        }
        public function conectar(){
            $this->mysqli = new mysqli('localhost','root','','escritor');
        }
        public function validarUsuario(){
            $sql = "SELECT * FROM user WHERE email='$this->email' and senha='$this->senha'";
            $resultado = $this->mysqli->query($sql);

            if(!$resultado){$this->erro();}

            if($resultado->num_rows == 0){
                echo "nao existe usuario";
            }else{
                echo "existe usuario";
            }
        }
        public function insertUsuario(){
            $sql = "SELECT * FROM user WHERE email='$this->email'";
            $resultado = $this->mysqli->query($sql);

            if(!$resultado){
                $this->erro();
            }

            if($resultado->num_rows == 1){
                echo "email em uso";
                exit();
            }

            $sql = "INSERT INTO user(nome,email,senha) VALUES('$this->nome','$this->email','$this->senha')";
            $resultado = $this->mysqli->query($sql);

            if(!$resultado){
                $this->erro();
            }

            echo "registrado com sucesso";
        }
        public function erro(){
            echo "<p>Erro</p>";
            exit();
        }
    }
?>

Would some form of the script get smaller and "prettier"?

Thank you in advance!

    
asked by anonymous 25.03.2018 / 18:33

1 answer

1

There is no one right, nor can making the smaller code ever help you (for example, the lack of Try Catch can hinder the handling of errors). Other Examples:

  • Create a class to store the Scripts SQL separated and make the bindings;
  • Do not concatenate $ this-> with the query as it may result in Injection link
  • In case of Remove or Update , always return true on success, or false, if the database fails, bringing the responsibility of handling the results to the servlet, or another layer that called this method;
  • In case of Insert , you can return the ID of the newly created record in the database, so you will need to work with the transaction;
  • Always use Try Catch to handle exceptions every time you make a connection to the database;
  • (optional) Prefer to use PDO instead of Mysqli , as a matter of being Object Oriented, and work with several different databases. MySQL vs PDO - what is the most recommended to use? .
  • Example:

        public function conectar(){
            $this->connection = new PDO("mysql:host=localhost;dbname=escritor", "root", ""); 
        }
        public function insertUsuario(){
            try{
              $this->connection->beginTransaction();
              $stmt = Sqls::insercaoUsuarios($this->connection,$this->email,$this->nome,$this->senha);
              if($stmt->execute()){
                  $lastid = $this->connection->lastInsertId();
                  $this->connection->commit();
                  return $lastid;
               }
            } catch(PDOExecption $e) { 
               $this->connection->rollback(); 
               echo $e->getMessage(); 
            } 
            return false;
        }
    

    In the Sqls :: insercaoUsuarios case you will only perform the creation of a PDO statement, ready to be executed.

    $ this-> connection would be from the PDO class that connects to the database, and $stmt from the PDOStatement class

        
    25.03.2018 / 18:45