Help with insert on Mvc php

Hi guys, im a student and i’m learning mvc on my php class. My school work is to make insert/update and delete using mvc. This is my folder structure.Screenshot_1 .

On controllers/Brawler i have this function.
> public function insert() {

    $Brawlers = $this->model('Brawlers'); // é retornado o model Brawlers()
    $data = $Brawlers::inserir($_POST, $_FILES);
    $this->view('brawler/insert', ['brawlers' => $data]);

On models/Brawlers i have

public static function inserir($post, $files){
       // tratamento dos erros
       $post = $_POST;
       $files = $_FILES;

       if (isset($_POST['name']) && isset($_POST['rarity']) && isset($_POST['role']) && isset($_POST['health']) && isset($_POST['speed']) && isset($_FILES['image'])) {

       if ($_FILES['image']['error'] > 0) {
           echo 'Problema: <br />';
           switch ($_FILES['image']['error'])
               case 1: echo 'Ficheiro excedeu o tamanho máximo especificado em php.ini'; break; 	// do PHP
               case 2: echo 'Ficheiro excedeu o tamanho máximo especificado pelo aributo MAX_FILE_SIZE do formulário HTML'; break; 			// do HTML
               case 3: echo 'Ficheiro apenas parcialmente carregado [corrompido]'; break;			// falhou
               case 4: echo 'Ficheiro não foi carregado'; break;						// falhou

       $name = $_POST['name'];
       $rarity = $_POST['rarity'];
       $role = $_POST['role'];
       $health = $_POST['health'];
       $speed = $_POST['speed'];
       $image = $_FILES['image']['name'];
       $image_caminho = "imgs/" . $image;
       $ativo = 1;

       // se existe o ficheiro uploaded
       if (is_uploaded_file($_FILES['image']['tmp_name'])) { // neste caso, o registo em base de dados apenas é efetuado se houver ficheiro

           // verificar se o ficheiro já existe no servidor (na pasta do projeto)
           // no caso de existir, o nome do ficheiro é alterado sendo concatenado com o timestamp
           if (file_exists($image_caminho)) {
               $image = time() . $image;
               $image_caminho = "imgs/" . $image;

           // move-o para o destino
           if (move_uploaded_file($_FILES['image']['tmp_name'], $image_caminho)) { // foi feito o upload do ficheiro com sucesso para a pasta destino
               // registar informação em base de dados
               $sql="INSERT INTO brawlers (name, rarity, role, health, speed, image) VALUES (?,?,?,?,?,?)";

               /* Prepare statement */
               $stmt = $conn->prepare($sql);
               if($stmt === false) {
                   trigger_error('Problema com o SQL: ' . $sql . ' Erro: ' . $conn->error, E_USER_ERROR);
               } else {
                   /* Bind parameters. Types: s = string, i = integer, d = double,  b = blob */
                   $stmt->bind_param('ssssss', $name, $rarity, $role, $health, $speed, $image);

                   /* Execute statement */

                   if ($stmt->affected_rows > 0) {
                       echo "<div><b>Utilizador registado com sucesso.</b></div>" ;
                       echo "<div><img src='" . $image_caminho . "'></div>" ;



           } else {
               echo 'Problema: Impossível mover para destino final';
       } else {
           echo 'Problema: Filename: ';
           echo $_FILES['image']['name'];

And on Views/insert i have

<div style="padding-top: 40px;">

                <h1>Criação de novo utilizador</h1>
                <form action="./insert" method="post" enctype="multipart/form-data">
                    <input type="hidden" name="MAX_FILE_SIZE" value="1000000">
                      <div><input type="text" name="name" id="name"></div>
                      <div><input type="text" name="rarity" id="rarity"></div>
                      <div><input type="text" name="role" id="role"></div>
                      <div><input type="text" name="health" id="health"></div>
                      <div><input type="text" name="speed" id="speed"></div>
                      <div><input type="file" name="image"></div>
                    <div style="margin-top: 20px;">
                        <button type="submit">Enviar formulário</button>

                <a href="../">Voltar para pagina inicial</a></li>


I’m trying to make the insert, but its not working. When i click submit nothing happpens. Can someone help me with this? Thank you and sorry for my bad english.

Is that really the case? Is the page not even reloading or redirecting to “./insert”? Press F12 and have a look in the network tab. I don’t really see how “./insert” should go into the code you posted, there must be some kind of router involved. Does any code run, do you get an output from var_dump() anywhere? Looks like you are using MySQLi, so you should enable error reporting for that


Yes i can run the “./insert” page, i get this
but like i said, when i click submit it does not add the new user.
when i use var_dump($_POST) the result on insert is “array(0) { }”. Only the insert is not working, the get and index works fine.

ok, now when i submit i get this error.

**Notice** : Undefined variable: conn in  **E:\xampp\htdocs\brawlstarsteste\app\models\Brawlers.php**  on line  **81**

**Fatal error** : Uncaught Error: Call to a member function prepare() on null in E:\xampp\htdocs\brawlstarsteste\app\models\Brawlers.php:81 Stack trace: #0 E:\xampp\htdocs\brawlstarsteste\app\controllers\Brawler.php(37): app\models\Brawlers::inserir(Array, Array) #1 [internal function]: Brawler->insert() #2 E:\xampp\htdocs\brawlstarsteste\app\core\App.php(35): call_user_func_array(Array, Array) #3 E:\xampp\htdocs\brawlstarsteste\index.php(5): app\core\App->__construct() #4 {main} thrown in  **E:\xampp\htdocs\brawlstarsteste\app\models\Brawlers.php**  on line  **81**

makes sense, you did not provide $conn to the function.

I removed “$post, $files” from the function “inserir()” on models/Brawlers and now on my views/insert when i use “var_dump($_POST);” my result is this

array(6) { [“MAX_FILE_SIZE”]=> string(7) “1000000” [“name”]=> string(4) “Mike” [“rarity”]=> string(6) “Common” [“role”]=> string(6) “Healer” [“health”]=> string(3) “700” [“speed”]=> string(4) “1000” }

but it does not add on database. even when i create the $conn.


show your modified code

Sponsor our Newsletter | Privacy Policy | Terms of Service