Return true or false PHP

2

I realized that the validation did not work and that no matter what data you enter from the maintainer, this code always returns 1. What I'm looking for is that it returns 0 if the sql query did not return any results.

if (!$cnn) {
    die("Conexion Fallida: " . mysqli_connect_error());
  }else {
    $nombre_usuario = $_POST['txt_nombre_admin']; //Nombre del usuario
    $contraseña_usuario = $_POST['txt_password_admin'];//Contraseña usuario
    $privilegio_usuario = $_POST['sel_privilegio']; //Nivel del usuario

    $rs = mysqli_prepare($cnn,"SELECT privilegio FROM usuarios WHERE (nombre = ? and password = ? and privilegio = ?)");
    $ok = mysqli_stmt_bind_param($rs, "ssi", $nombre_usuario, $contraseña_usuario, $privilegio_usuario);
    $ok = mysqli_stmt_execute($rs); //Siempre da 1

    if ($ok == false) {
      echo $ok; 
    }else {
      echo $ok;
    }
    
asked by Sebastian Ismael 27.11.2018 в 16:51
source

1 answer

1

The verification of the existence of data can not be dependent on the success or failure of any function. The correct thing would be to review the same data. You can do it for example by means of a query COUNT(*) . If you are interested in information about any column of the table, then you can do a% normal% of those columns and at the same time determine the existence of data by SELECT . In either case the verification would be done on the data itself.

I propose this code:

$ok=FALSE;
if (!$cnn) {
    die("Conexion Fallida: " . mysqli_connect_error());
} else {
    $nombre_usuario = ( empty ($_POST['txt_nombre_admin']) )   ? NULL : $_POST['txt_nombre_admin'];
    $clave_usuario = ( empty ($_POST['txt_password_admin']) )  ? NULL : $_POST['txt_password_admin'];
    $privilegio_usuario = ( empty ($_POST['sel_privilegio']) ) ? NULL : $_POST['sel_privilegio'];

    if ($nombre_usuario && $clave_usuario && $privilegio_usuario){
        $sql="SELECT COUNT(*) total FROM usuarios WHERE nombre = ? AND password = ? AND privilegio = ?";
        if ($rs = mysqli_prepare($cnn,$sql)){
            $stmt = mysqli_stmt_bind_param($rs, "ssi", $nombre_usuario, $clave_usuario, $privilegio_usuario);
            mysqli_stmt_execute($rs);
            mysqli_stmt_bind_result($rs, $numFilas);
            $ok= ($numFilas > 0) ? TRUE : FALSE;
        }else{
            echo "Error preparando la consulta";
        }
    }else{
        echo "No se pasaron los datos completos en el POST";
    }
}
echo $ok;

In a controlled code, which always informs of what has happened. In addition, it verifies the data that exists in POST through ternary operators. It has the variable num_rows in $ok by default and will only change when there are rows in the query.

    
answered by 27.11.2018 / 17:19
source