Doubt about changing data in PHP MVC

Asked

Viewed 82 times

-2

I need to update a client’s data on my MVC project. It is a form that must update two tables in the database: "user" and "patio", but only "user" is being updated, which can be?

Returns no error, only there is no update of the street in the bank.

This is the form that takes the new data


<form action="<?= url("admin/usuario/salvar") . "/" . $data[0]['cod_usu']?>" method="post">
        <div style="border-radius: 5px;
                    border-style: solid;
                    border-color: cyan;
                    border-widht: 1px;
                    padding: 10px;
                    margin-top: 10px;
                    margin-bottom:10px;";>

<?php if($data[0]['cod_status_usu'] == 'A'): ?>
        <label class="container">Ativo
            <input type="radio" checked name="cod_status_usu" value="A">
            <span class="checkmark"></span>
        </label>

        <label class="container">Inativo
            <input type="radio" name="cod_status_usu" value="I">
            <span class="checkmark"></span>
        </label>

    <?php else:?>
            <label class="container">Ativo
            <input type="radio" name="cod_status_usu" value="A">
            <span class="checkmark"></span>
        </label>

        <label class="container">Inativo
            <input type="radio" checked name="cod_status_usu" value="I">
            <span class="checkmark"></span>
        </label>
        
     <?php endif; ?>
        </div>
        <div class="form-group">
            <label for="inputAdress">Email</label>
            <input type="text" class="form-control" id="email" name="email" value="<?=$data[0]['email_usu']?>" placeholder="" disabled>
        </div>
        <div class="form-group">
            <label for="inputAdress">Nome de Usuario</label>
            <input type="text" class="form-control" id="nomeUsuario" name="nomeUsuario" value="<?=$data[0]['nome_usu']?>" placeholder="" disabled>
        </div>
        <div class="form-row">
            <div class="form-group col-md-4">
                <label for="inputZip">CEP</label>
                <input type="text" class="form-control cep-mask" name="cep" maxlength="9" OnKeyPress="formatar('#####-###', this)" value="<?=$data[0]['cep_logra'] ?>">
            </div>
            <div class="form-group col-md-4">
                <label for="inputCity">Numero</label>
                <input type="text" class="form-control" id="numero" name="numero" value="<?=$data[0]['num_logra'] ?>" readonly>
            </div>
        </div>
        <div class="form-group">
            <label for="inputAdress">Complemento</label>
            <input type="text" class="form-control" id="complemento" name="complemento" value="<?=$data[0]['compl_logra'] ?>" placeholder="" readonly>
        </div>
        <div class="modal-footer">
            <button type="submit" class="btn btn-primary">Salvar</button>
        </div>
    </form>

Esté is the code in the Admincontroller (partial)

public function user($data): void {
        try {

            $usuario = new Usuario();
            $usuario->setCod_usu($data['cod_usu']);
            $usuarioDao = new UsuarioDao();

            $data = $usuarioDao->readUserId($usuario);
            $toView = new ToView(URL_VIEW_ADMIN);
            $toView->viewStandard('usuario', $data);

        } catch (\Exception $exception) {
            //throw $th;
        }
    }

    public function saveUser($data): void{
        try {
          $data = filter_var_array($data, FILTER_SANITIZE_STRIPPED);


          $usuario = new Usuario();
          $usuario->setCod_usu($data['cod_usu']);
          $usuario->setCod_status_usu($data['cod_status_usu']);
  
          $usuarioDao = new UsuarioDao();
          $usuarioDao->updateUserId($usuario);
          $data = $usuarioDao->readUserId($usuario);
          $toView = new ToView(URL_VIEW_ADMIN);
          $toView->viewStandard('usuario',$data);
          
        } catch (\Exception $exception){
  
        }
  }

  public function saveUserLogra($data): void{
    try {
      $data = filter_var_array($data, FILTER_SANITIZE_STRIPPED);

      $lo = new Logradouro();
      $lo->setCod_logra($data['cod_logra']);
      $lo->setCep_logra($data['cep_logra']);
      $lo->setNum_logra($data['num_logra']);
      $lo->setCompl_logra($data['compl_logra']);

      $loDao = new LogradouroDao();
      $loDao->updateLograId($lo);

      
    } catch (\Exception $exception){

    }
}

This is the User (partial)

    public function read() {
        try {
            $sql = "SELECT cod_tipo_usu,cod_usu, nome_usu,  cep_logra, email_usu, tel_usu, cod_status_usu from usuario
            inner join logradouro on usuario.cod_logra = logradouro.cod_logra";
            $stmt = Conexao::getConn()->prepare($sql);
            $stmt->execute();
            
            if($stmt->rowCount() > 0) {
                $result = $stmt->fetchAll(\PDO::FETCH_ASSOC);
                return $result;
            }else{
                return [];
            }      
          } catch (\PDOException $exception) {
            throw $exception;
    }

    }

    public function readUserId(Usuario $user) {
        try {
            $sql = "SELECT * FROM usuario inner join logradouro on usuario.cod_logra = logradouro.cod_logra WHERE cod_usu = ?";
            $stmt = Conexao::getConn()->prepare($sql);
            $stmt->bindValue(1, $user->getCod_usu());
            $stmt->execute();
            
            if($stmt->rowCount() > 0) {
                $result = $stmt->fetchAll(\PDO::FETCH_ASSOC);
                return $result;
            }else{
                return [];
            }      
          } catch (\PDOException $exception) {
            throw $exception;
    }

    }

    

    public function updateUserId(Usuario $user) {
        try {
            $sql = "UPDATE usuario SET cod_status_usu = ?
                                          WHERE cod_usu = ?"; 
            $stmt = Conexao::getConn()->prepare($sql);
            $stmt->bindValue(1, $user->getCod_status_usu());
            $stmt->bindValue(2, $user->getCod_usu());
            
            return $stmt->execute();
              
          } catch (\PDOException $exception) {
            throw $exception;
    }

    }

This is Logradourodao (partial)

 public function updateLograId(Logradouro $lo) {
        try {
            $sql = "UPDATE logradouro SET cep_logra = ?,
                                          num_logra = ?,
                                          compl_logra = ?
                                        WHERE cod_logra = ?";
            $stmt = Conexao::getConn()->prepare($sql);
            $stmt->bindValue(1, $lo->getCep_logra());
            $stmt->bindValue(2, $lo->getNum_logra());
            $stmt->bindValue(3, $lo->getCompl_logra());
            $stmt->bindValue(4, $lo->getCod_logra());

            return $stmt->execute();
             
          } catch (\PDOException $exception) {
            throw $exception;
    }

    }

UsuarioDao LogradouroDao AdminControlle (1) AdminControlle (2)

  • Assuming this url admin/usuario/salvar is resolved to perform the action public function saveUser($data), the backyard will never really be updated, because within this function you only have code running changes in the User.

  • Hi, sorry for the delay. I am using these two lines in my index.php, would something be wrong? $router->post("/usuario/save/{cod_logra}","Admincontroller:saveUserLogra"); $router->post("/usuario/save/{cod_usu}","Admincontroller:saveUser");

  • The question does not seem to be in the route but inside the action (function of the controller that executes the code)

1 answer

1


For what you put in the comment only one of the actions is executed, you are waiting for both routes to be executed but - thinking of the routing implementation patterns, only one is because when passing segment configuration with different variable but same url base to route, the routing parser is probably identifying only one of them:

$router->post("/usuario/salvar/{cod_logra}","AdminController:saveUserLogra"); 
$router->post("/usuario/salvar/{cod_usu}","AdminController:saveUser");

The parser sees: /usuario/salvar/{UMAVARIAVEL}

A possible solution, thinking that your change screen has both the fields to change user and to change venue, just leave the route to save user

In his index php.

$router->post("/usuario/salvar/{cod_usu}","AdminController:saveUser");

And in *Admincontroller_ unify the saveUser and Savelogra functions:

public function saveUser($data): void{
         $data = filter_var_array($data, FILTER_SANITIZE_STRIPPED);

        // SALVANDO USUÁRIO
        try {
          $usuario = new Usuario();
          $usuario->setCod_usu($data['cod_usu']);
          $usuario->setCod_status_usu($data['cod_status_usu']);
  
          $usuarioDao = new UsuarioDao();
          $usuarioDao->updateUserId($usuario);
          
        } catch (\Exception $exception){
  
        }

    // SALVANDO LOGRA
    try {
      $lo = new Logradouro();
      $lo->setCod_logra($data['cod_logra']);
      $lo->setCep_logra($data['cep_logra']);
      $lo->setNum_logra($data['num_logra']);
      $lo->setCompl_logra($data['compl_logra']);

      $loDao = new LogradouroDao();
      $loDao->updateLograId($lo);

      
    } catch (\Exception $exception){

    }

     $data = $usuarioDao->readUserId($usuario);
     $toView = new ToView(URL_VIEW_ADMIN);
     $toView->viewStandard('usuario',$data);

}
  • I followed your tip and the following error happened: "Notice: Undefined index: cod_usu in C: xampp htdocs projeto-kdovo src App Admincontroller.php on line 86" .

  • Part of the code where the error points: public function user($data): void {&#xA; try {&#xA;&#xA; $usuario = new Usuario(); (line 86) $usuario->setCod_usu($data['cod_usu']); $usuarioDao = new UsuarioDao();&#xA;&#xA; $data = $usuarioDao->readUserId($usuario);&#xA; $toView = new ToView(URL_VIEW_ADMIN);&#xA; $toView->viewStandard('usuario', $data);&#xA;&#xA; } catch (\Exception $exception) {&#xA; //throw $th;&#xA; }&#xA; }

  • When pulling the line: $router->get("/usuario/{cod_logra}","AdminController:user");, the code has no error so far, but when trying to save the data and update the two tables, the following error appears: "Notice: Undefined index: cod_logra in C: xampp htdocs projeto-kdovo src App Admincontroller.php on line 118", and only the user table is changed.

  • You need to validate the codes coming from the interface and the origin of these variables, see, I pointed out a possible solution to the logic of your initial question. To help you with the code in detail by debugging all changes, the ideal would be to contact private.

Browser other questions tagged

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