Get a single value of MySQL and store it in a variable with PHP

0

I need help to understand something basic. I have searched everywhere but the answers have not been simple. I have been trying to validate a specific type of user with ID_Profile = 001 to be redirected to "MenuExamenes.php" and users with ID_Profile = 002 that are redirected to "MenuPrincipal.php." I really do not know if it is possible to do something as simple as storing a single value, obviating that it will store the first value it finds ... or the last one. In this case it is a single value so it is not important.

ID_Profile is in the BD an int (3). (I know that this is the least optimal option to do it, it is for a learning project, not real life).

I have a config.php:

<?php
define('DB_SERVER', 'localhost:8889');
define('DB_USERNAME', 'root');
define('DB_PASSWORD', 'root');
define('DB_DATABASE', 'ProgramaPruebas');
$db = mysqli_connect(DB_SERVER,DB_USERNAME,DB_PASSWORD,DB_DATABASE);
?> 

And I have my login.php

 <?php
 include("config.php");
 if($_SERVER["REQUEST_METHOD"] == "POST") {

 $myusername =        mysqli_real_escape_string($db,$_POST['user_nickname']);
  $mypassword = mysqli_real_escape_string($db,$_POST['password']); 



  $sqlusertype = "SELECT ID_Perfil FROM Usuarios WHERE user_nickname =      '$myusername' and password = '$mypassword";
  $result1 = mysqli_query($sqlusertype, $db);


  $sql = "SELECT User_Id FROM Usuarios WHERE user_nickname =      '$myusername' and password = '$mypassword'";
   $result = mysqli_query($db,$sql);


    $count = mysqli_num_rows($result);



if($count == 1 && result1 == 001 ) {



echo '<script type="text/javascript">
alert("Inicio de Sesión Exitoso");
window.location.href="MenuExamenes.php";

</script>';

 alert("Inicio de Sesión Exitoso");

 }
 elseif($count == 1 && result1 == 002 ){
 echo '<script type="text/javascript">
 alert("Inicio de Sesión Exitoso");
 window.location.href="MenuPrincipal.php";

 }else{
 $error = "El usuario/contraseña son incorrectos";
   }
  }
 ?>
    
asked by Iv Ramírez 10.12.2018 в 08:29
source

2 answers

0

To extract the result of the column in each query:

 $sqlusertype = "SELECT ID_Perfil FROM Usuarios WHERE user_nickname =      '$myusername' and password = '$mypassword";
 $result1 = mysqli_query($sqlusertype, $db);
$id_perfil = -1;
if ($result1) {
    if (mysqli_num_rows($result1)) {
        $row = mysqli_fetch_assoc($result1);
        $id_perfil = $row['ID_Perfil'];
    }
} else {
    echo "error en la cosulta<br />";
}


 $sql = "SELECT User_Id FROM Usuarios WHERE user_nickname =      '$myusername' and password = '$mypassword'";
 $result = mysqli_query($db,$sql);
$user_id = -1;
if ($result) {
    if (mysqli_num_rows($result)) {
        $row = mysqli_fetch_assoc($result);
        $user_id = $row['User_Id'];
    }
} else {
    echo "error en la cosulta<br />";
}

Note: you have an error in:

echo '... window.location.href="MenuPrincipal.php";

you can correct it by adding:; '

echo '... window.location.href="MenuPrincipal.php";';

It is not a good practice to use javascript in this way to redirect from a php script. In any case you can implement this method:

header('Location: MenuPrincipal.php');

header('Location: /path/MenuPrincipal.php');

This expression "result1 == 001" is the same as "result1 == 1" since it is an integer. If "ID_Profile" or "User_Id" returns an integer there will be no problem, but if it is a string, I advise you to convert it to an integer using this function:

$user_id_int = intval($user_id);  

echo intval('001');  // devuelve 1

By doing this conversion, you can now change the expression to:

if($count == 1 & result1 === 1){...} 

It is a good practice to use === instead of == since you ensure that it is only true if it is an integer and not a string converted to an integer during the evaluation of the expression.

I advise you to prepare the SQL statements with bind_param (); to avoid SQLinjection, type errors and other problems, in addition to having the cleanest and readable code.

link

link

    
answered by 10.12.2018 в 15:59
0

Simplifying the code to make it as readable as possible is as follows:

  • We simplify the query by bringing both fields in a single query
  • we get the data in an object
  • we evaluate the value of the ID_Profile field
  • We redirect to the right place
  • <?
    
        //incluir archivo de configuración
        include("config.php");
    
        $myusername = mysqli_real_escape_string($db,$_POST['user_nickname']);
        $mypassword = mysqli_real_escape_string($db,$_POST['password']); 
    
        $sql = "SELECT User_Id,ID_Perfil FROM Usuarios WHERE user_nickname = '$myusername' and password = '$mypassword";
    
        //ejecutar consulta contra la BD trayendo ambos campos en una sola consulta optimizando los recursos del servidor
        $result = mysqli_query($db,$sql);
    
        if(mysqli_num_rows($result)>0){
    
            //obtenemos el registro completo del usuario con todos los campos en un objeto
            $r=mysqli_fetch_object($result);
    
            //evaluamos el ID_Perfil y redireccionamos
            //si almacenas datos enteros debes tratarlos como enteros (1,2) a menos que sean de tipo varchar ('001, '002')
            switch($r->ID_Perfil){
                case 1:
                    header("Location: MenuExamenes.php");
                case 2:
                    header("Location: MenuPrincipal.php");
            }
        }
    
        
    answered by 10.12.2018 в 16:39