0

I am doing a login, where first I do the select query to know if a username is already registered in my database, then I do an if ($stmt->num_rows()===0) if true I insert the username and password but I could not by error Fatal error:

Uncaught Error: Call to a member function bind_param() on bool.

Thanks in advance

PHP

    if ($accion === 'crear') {
     //Codigo para crear los administradores


     //importar la conexion
    include '../funciones/conexion.php';

    try{
        //Realizar la consulta a la base de datos
        $stmt =$conexion->prepare('SELECT usuario FROM usuarios 
        WHERE usuario =?');
        $stmt->bind_param('s', $usuario);
        $stmt->execute();
        
        if ($stmt->num_rows()===0) {
            //Hashear passwords

            $opciones = array('cost' => 12);

            $hash_password = password_hash($password, 
             PASSWORD_BCRYPT, $opciones);

            $sql=$conexion->prepare("INSERT INTO usuarios (usuario, 
              password) VALUES (?, ?)");
             $sql->bind_param('ss', $usuario , $hash_password);
             $sql->execute(); 
             $respuesta = array(
                'respuesta' =>'correcto',
                );
            
              }         
        

            //Si el usuario existe
           
            else {
                    $respuesta = array(
                        'respuesta' => 'Usuario Existe');
             }
          
        $sql->close();
        $stmt->close();
        $conexion->close();   
        }catch(Exception $e){
        //En caso de un error, tomar la excepcion
        $respuesta = array('pass' =>$e->getMessage() );
         }
     echo json_encode($respuesta); 
}

javascript

function validarRegistro(e){
       e.preventDefault();

    var usuario = document.querySelector('#usuario').value,
        password = document.querySelector('#password').value,
        tipo = document.querySelector('#tipo').value;

    if (usuario === '' || password === '') {
        //la validacion falló
        swal({
            type: 'error',
            title: 'Error!',
            text: 'Usuario y/o Password están en blanco'
        })
    } else {
        //Ambos campos son correctos, mandar a ejecutar Ajax
        
        //datos que se envian al servidor
        var datos = new FormData();
        datos.append('usuario', usuario);
        datos.append('password', password);
        datos.append('accion', tipo);

        // crear el llamado a ajax
        var xhr = new XMLHttpRequest();

        //abrir la conexion 
        xhr.open('POST', 'inc/modelos/modelo-admin.php', true);

        //retorno de datos
        xhr.onload=function(){
            if (this.status === 200) {
                var respuesta = (JSON.parse(xhr.responseText));

          console.log(respuesta);
                //Si la respuesta es correcta
                if (respuesta.respuesta === 'correcto') {

                    //Si es un usuario nuevo
                    if (respuesta.tipo === 'crear') {
                        swal({
                            title: 'Usuario Creado',
                            text: 'El usuario se creó 
                exitosamente',
                            type: 'success'

                        });
                    } 
                                        
                }else{
                      //Hubo un error
                        swal({
                            title: 'Error',
                            text: 'Usuario ya existe',
                            type: 'error'

                        });
                    }
            }
        }

        //Enviar la peticion
        xhr.send(datos);
    }    
}
Paul T.
  • 4,703
  • 11
  • 25
  • 29
  • The `function bind_param() on bool` portion of the error means that `prepare` did not return a `statement` object, but failed somehow and false was returned. Which `bind_param` is failing ... the one before the number of rows check, or the other one? (sounds like the insert query?) ... might also try adding `mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);` at the top of the script to see if that might give additional details. – Paul T. Aug 13 '22 at 02:56
  • The one that gives the error is the second one, when I want to insert data to MySQL. Thanks for your answer, I will try your comment – Kenlymar Paredes Aug 13 '22 at 15:47
  • Also to column `password`, try adding backticks to that column name: `\`password\`` – Paul T. Aug 13 '22 at 16:30
  • I used the mysqli report and it gives me "Comands out of sync; You can't run this command now", Any ideas? – Kenlymar Paredes Aug 13 '22 at 21:21
  • Is there any more to the error message after that? ... that error can have many reasons, but there should be a little more info after `now`. – Paul T. Aug 13 '22 at 21:52
  • thanks for the help, I solved with mysqli_stmt_store_result($stmt); – Kenlymar Paredes Aug 14 '22 at 00:08
  • Cool, thanks for the update, and posting your resolve! – Paul T. Aug 14 '22 at 00:40

0 Answers0