Error in my PHP document

1

I'm having a small problem trying to insert some data in my database, but I could not find the respective error:

ERROR

  


\ n Fatal error : Uncaught Error: Call to undefined method   mysqli_stmt :: bindParam () in   C: \ xampp \ htdocs \ MyApp \ mainApp \ Create \ registerBusiness.php: 18 \ nStack   trace: \ n # 0 {main} \ n thrown in    C: \ xampp \ htdocs \ MyApp \ mainApp \ Create \ registerBusiness.php   on line 18
\ n

PHP CODE

<?php
  header("Context-type: application/json;");
  require '../conexion.php';
  $data = json_decode(file_get_contents("php://input"));
  //Objeto convertido a formato UTF8 para insertar caracteres especiales en la BD del sistema
  $mysqli->set_charset('utf8');
  $nombreEmpresa    = mysqli_real_escape_string($mysqli, $data->nombre_empresa);
  $rutEmpresa       = mysqli_real_escape_string($mysqli, $data->rut_empresa);
  $direccionEmpresa = mysqli_real_escape_string($mysqli, $data->direccion_empresa);
  $giroEmpresa      = mysqli_real_escape_string($mysqli, $data->giro_empresa);
  $telefonoEmpresa  = mysqli_real_escape_string($mysqli, $data->telefono_empresa);
  $celularEmpresa   = mysqli_real_escape_string($mysqli, $data->celular_empresa);

  //Prepramos la consulta para INSERTAR datos en a BD a la tabla empresa
  $insertar_empresa = $mysqli->prepare("INSERT INTO empresa(nombre_empresa, rut_empresa, direccion_empresa, giro_empresa, telefono_empresa, celular_empresa)
                                        VALUES (':nombreEmpresa', ':rutEmpresa', ':direccionEmpresa', ':giroEmpresa', ':telefonoEmpresa', ':celularEmpresa')");
  //Usamos el metodo bindParam() para captar las variables en la BD
  $insertar_empresa->bindParam(':nombreEmpresa', $nombreEmpresa);
  $insertar_empresa->bindParam(':rutEmpresa', $rutEmpresa);
  $insertar_empresa->bindParam(':direccionEmpresa', $direccionEmpresa);
  $insertar_empresa->bindParam(':giroEmpresa', $giroEmpresa);
  $insertar_empresa->bindParam(':telefonoEmpresa', $telefonoEmpresa);
  $insertar_empresa->bindParam(':celularEmpresa', $celularEmpresa);
  $insertar_empresa->execute();

  //Ejecutamos la consulta
  if ($insertar_empresa->execute())
  {
    $resultado = array('mensaje' => ''/*,'variable' => 0*/);
    $resultado['mensaje'] = "Se ha registrado correctamente la Empresa.";
    echo json_encode($resultado);
  }
  else
  {
    $resultado = array('mensaje' => ''/*,'variable' => 0*/);
    $resultado['mensaje'] = "Ha ocurrido un error: " . $mysqli->error;
    echo json_encode($resultado);
  }
 ?>

Beforehand, thank you very much!

    
asked by jecorrales 02.07.2018 в 03:16
source

1 answer

4

Your code has several errors, I list them here as I have seen and in the end I propose a solution:

  • This is not an error, but you do not need to use mysqli_real_escape_string for prepared queries. Precisely prepared queries are responsible for escaping any cheating data. You can leave it if you want, but that means overloading the code only and risking the function modifying some data.
  • In the insert you had one more column, which was the ID of the company. That was the main reason for the initial failure, because the query was wrong.
  • The bind_param method of mysqli does not work as bindParam of PDO. They are two different APIs. First mysqli does not support :nombre markers, only ? placeholders. Second in the bind_param you must pass in quotation marks the data type of each column that participates in the prepare and then the value of each column using a variable.
  • You were using execute twice.
  • You made a strange use of the array that collects the answer.
  • You innocently said that the company was added. You can not say without checking if there were rows affected.
  • You can do echo of the array at the end of the whole, once.
  • I've also put a control on the connection itself.
  • ... I do not remember if I corrected something else.

Here is the code. It should work. If you give an error, comment:

<?php  
  $data = json_decode(file_get_contents("php://input"));
  $resultado=array();
  if ($mysqli)
  {
      //Objeto convertido a formato UTF8 para insertar caracteres especiales en la BD del sistema
      $mysqli->set_charset('utf8');
      $nombreEmpresa    = $data->nombre_empresa;
      $rutEmpresa       = $data->rut_empresa;
      $direccionEmpresa = $data->direccion_empresa;
      $giroEmpresa      = $data->giro_empresa;
      $telefonoEmpresa  = $data->telefono_empresa;
      $celularEmpresa   = $data->celular_empresa;

      //Prepramos la consulta para INSERTAR datos en a BD a la tabla empresa
      $sql="INSERT INTO empresa (
                                    nombre_empresa, 
                                    rut_empresa, 
                                    direccion_empresa, 
                                    giro_empresa, 
                                    telefono_empresa, 
                                    celular_empresa
                                )
                         VALUES (   ?, 
                                    ?, 
                                    ?, 
                                    ?, 
                                    ?, 
                                    ?
                                )";
      $insertar_empresa = $mysqli->prepare($sql);

      //Usamos el metodo bind_param() para captar las variables en la BD
      /*
          *Las 'ssssss' representan el tipo de dato, 
          *asumo que todas son varchar en la base de datos
          *si alguno es numérico, debes poner una i en su posición
      */
      $insertar_empresa->bind_param('ssssss', $nombreEmpresa,$rutEmpresa,$direccionEmpresa,$giroEmpresa,$telefonoEmpresa,$celularEmpresa);

      //Ejecutamos la consulta
      if ($insertar_empresa->execute())
      {
        /*
           *Verificamos si hubo filas afectadas
           *y decidimos el estado del mensaje con un operador ternario
        */
        $insertedRows=$insertar_empresa->affected_rows;  
        $mensaje=($insertedRows > 0) ? "Se ha registrado correctamente la Empresa." : "No fue posible la inserción. Error: ".$insertar_empresa->error;  
        $resultado['mensaje'] = $mensaje;
      }
      else
      {
        $resultado['mensaje'] = "Ha ocurrido un error: " . $mysqli->error;
      }

    }
    else
    {    
        $resultado['mensaje'] = "No hay conexión a la BD";
    }

    echo json_encode($resultado);

 ?>
    
answered by 02.07.2018 / 03:59
source