MySQLi -insert_id returns value "0"

0

I have a management panel in which you can add even more administrators, but when I try to add them, I get an error. I have reviewed multiple times the data sent with die(json_encode($_POST)); and if all the data of the form arrive, but every time I try die(json_encode($id_registro)); (more down you will see what this variable is) it returns "0" and therefore throws me an error. If more information is needed, I can upload it without problems.

include_once "funciones/funciones.php"; // esta es la conexión con la base de datos
$usuario = $_POST['usuario'];
$nombre = $_POST['nombre'];
$password = $_POST['password'];
$id_registro = $_POST['id_registro']; // variables globales
if ($_POST['registro'] == 'nuevo') { // este es el valor de un campo oculto que me indica el tipo de modificación a la base de datos
  $opciones = array(
    'cost' => 12
  );
  $password_hashed = password_hash($password, PASSWORD_BCRYPT, $opciones);
  try {
    $stmt = $conn->prepare("INSERT INTO admins (nombre, usuario, password) VALUES (?, ?, ?) "); //estoy seguro de que los nombres de la tabla y las columnas son correctos
    $stmt->bind_param("sss", $nombre, $usuario, $password_hashed);
    $stmt->execute();
    $id_registro = $stmt->insert_id;
    if ($id_registro > 0) {
      $respuesta = array( // esta es mi respuesta personalizada para AJAX
        'respuesta' => 'exito',
        'id_admin' => $id_registro
      );
    }else{
      $respuesta = array( //siempre me regresa esta respuesta
        'respuesta' => 'error'
      );
    }
    $stmt->close();
    $conn->close();
  } catch (\Exception $e) {
    echo "Error: " . $e->getMessage();
  }
die(json_encode($respuesta));// aqui se regresan valores a ajax
} // FIN-NUEVO

This is the AJAX that processes the personalized response.

  $('#guardar-registro').on('submit', function(e){
    e.preventDefault();
    var datos = $(this).serializeArray();
    $.ajax({
      type: $(this).attr('method'), // post, en este caso
      data: datos,
      url: $(this).attr('action'),
      dataType: 'json',
      success: function(data) {
        console.log(data);
        var resultado = data;
        if (resultado.respuesta == 'exito') {
          swal(
            'Correcto',
            'Se guardó correctamente',
            'success'
          )
        }else{
          swal(
            'Incorrecto',
            'Hubo un error al crear el administrador',
            'error'
          )
        }
      }
    })
  });

And this is the HTML of my form.

        <form role="form" name="guardar-registro" id="guardar-registro" method="post" action="modelo-admin.php">
          <div class="box-body">
            <div class="form-group">
              <label for="usuario">Usuario: </label>
              <input type="text" class="form-control" id="usuario" name="usuario" placeholder="Usuario">
            </div>
            <div class="form-group">
              <label for="nombre">Nombre: </label>
              <input type="text" class="form-control" id="nombre" name="nombre" placeholder="Nombre">
            </div>
            <div class="form-group">
              <label for="password">Contrase&ntilde;a: </label>
              <input type="password" class="form-control" id="password" name="password" placeholder="Password para iniciar sesión">
            </div>
            <div class="form-group">
              <label for="password">Repetir contrase&ntilde;a: </label>
              <input type="password" class="form-control" id="repetir_password" name="repetir_password" placeholder="Repetir password">
              <span id="resultado_password" class="help-block"></span>
            </div>
          </div>
          <!-- /.box-body -->

          <div class="box-footer">
            <input type="hidden" name="registro" value="nuevo">
            <button type="submit" class="btn btn-primary" id="crear_registro_admin">A&ntilde;adir</button>
          </div>
        </form>
    
asked by Angel Rivas 01.08.2018 в 00:19
source

1 answer

0

SOLVED My mistake was in the way I re-linked my database.

<?php
$conn = new mysqli('localhost', '**********', '*********', '***********');

if($conn->connect_error){
  echo $error -> $conn->connect_error;
}
?> // esta es la conexión original

And this is the way I tried to use that connection again

<?php
include_once '../funciones/conexion_bd.php';
?>

This is how it was corrected.

<?php
include_once '../../funciones/conexion_bd.php';
?>
    
answered by 01.08.2018 в 19:41