PHP MVC - How to run Model methods?

Asked

Viewed 314 times

0

Good afternoon!

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

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 Model (Sector.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 clicking the REGISTER button, I need to execute this method by sending the form. Do I need to go through the controller? And the form, sent through some URL in the action?

I stand by, thank you for any help.

  • 3

    Yes, that’s the controller’s function in MVC.

  • I believe this question is duplicate

  • I understood the question of going through the Controller. But, as I pass the form data as method parameters?

1 answer

2


To pass the data as parameter in the desired method, simply set an action in 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’ve helped :)

  • Mén! Very good and safe your answer.

Browser other questions tagged

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