Script "more beautiful"

Asked

Viewed 69 times

-2

I am using the following code for the User class :

<?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 have some form of script gets smaller and "more beautiful" ?

Thank you in advance!

  • I recommend: https://www.php-fig.org/ and https://www.owasp.org/

1 answer

1


There is no certain, not always making the code smaller can help you (example: the lack of Try Catch can harm the handling of errors). Other Examples:

  1. Create a class to store Scripts SQL separate and make the links;
  2. Not concatene $this->email with the query, as it may result in Injection https://www.tecmundo.com.br/tecmundo-explica/113195-sql-injection-saiba-tudo-ataque-simples-devastador.htm
  3. In case Remove or Update, always return true in case of success, or false in case of bank failure, bringing the responsibility of treating the results to Servlet, or another layer that called this method;
  4. In case Insert, you can return the ID, from the record that has just been created in the bank, for this you will need to work with transaction;
  5. Always use Try Catch to treat the exceptions every time you make any connection with the bank;
  6. (optional) Prefer to use PDO instead of Mysqli, for the sake of being Object-Oriented, and working with several different databases. Mysqli vs PDO - which 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 case Sqls::inserts.

$this->Connection would be Class PDO which makes the connection to the database, and $stmt class PDOStatement

  • can you show me how the script would look with your specifications ?

  • I thought the code would get bigger than that, but it was because check if there is already a user registration, you should put in separate method, matter of making reusable

  • Regarding the use of try catch, is only required in PDO, maybe you can make your code more organized using the DAO standard (but it’s opitional, no problem leaving as is), about the SQL Injection another link that can help. If you don’t want to exchange your database mysqli may be the best option for performance gain

Browser other questions tagged

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