PHP MVC - How to execute Model methods?

0

Good afternoon!

How do I execute a method of the Model class, in specific a method of insertion to the DB, in case I need to send the data of the Form.

This is the form in View (sector.php):

<form method="POST" enctype="multipart/form-data">
     <div class="form-group">
          <label for="nomesetor">Nome do setor:</label>
          <input id="nomesetor" name="nomesetor" type="text" class="form-control col-12 col-sm-12">
     </div>

     <a href="<?php echo BASE_URL; ?>" class="btn btn-danger">Cancelar</a>
     <button type="submit" class="btn btn-primary">Cadastrar</button>
</form>

The method I need to run in the Model (Set.php) is this:

public function addSetor ($nome) {
    $sql = $this->db->prepare("INSERT INTO setor SET nomesetor = :nome");
    $sql->bindValue(":nome", $nome);
    $sql->execute();
}

Anyway, when I click the REGISTER button, I need to execute this method by sending the form. Do I need to go through the controller? And the form, sending via some URL in the action?

I'm waiting, thanks for any help.

    
asked by anonymous 27.07.2018 / 21:01

1 answer

2

To pass the data as a parameter in the desired method, simply set an action on your form to the file, where it contains the Controller that has access to Your Model.

<form method="POST" enctype="multipart/form-data" action="caminho/seuController.php">

In your Controller you can check the $ _POST variable with the form data and call your method by passing the values as parameters.

if(isset($_POST['nomesetor']) && ! empty($_POST['nomesetor'])){
    $nomeSetor = $_POST['nomesetor']; /*não esqueça de escapar as informações por segurança ao inserir no banco de dados*/

    $this->addSetor($nomeSetor);
}

I hope I have helped:)

    
31.07.2018 / 03:35