How to capture the logged in user ID? PHP

Asked

Viewed 106 times

-2

My login code where after the (row > 0 ) try to select the id of the user who just logged in, I play the result in a variable and try assigned to a Session

$usuario = mysqli_real_escape_string($conexao, $_POST['usuario']);
$senha = mysqli_real_escape_string($conexao, $_POST['senha']);

$query = "select usuario from usuarios where usuario = '$usuario' and senha = md5('$senha')";

$result = mysqli_query($conexao, $query);

$row = mysqli_num_rows($result);

if($row > 0){

    $busca  = "select IDUSUARIO from usuarios where usuario = '$usuario' ";
    $identificacao = mysqli_query($busca);
    $retorno = mysqli_fetch_array($identificacao);

    $_SESSION['iduser'] = $retorno;
    
    $_SESSION['usuario'] = $usuario;
    header('Location: navegacao.php');
    exit();
}else{
    $_SESSION['nao_autenticado'] = true;
    header('Location: index.php');
    exit();
}

Here I try to assign this Session to a variable and through an Insert I try to insert this variable(user id) as a foreign key, but it is not working.

$fk = $_SESSION['iduser'];

$query = mysqli_query($conexao, "INSERT INTO imagens (imagem, tema, IDUSUARIO) VALUES ('$novonome', '$tema', '$fk')");
    
  • You are using session_start() before negotiating with session variables? I wonder why in the example you can see that you do not usesession_write_close() to save data and close the current session before leaving the page.

1 answer

1


You have to select the name of the column that is stored the user ID.

$_SESSION['iduser'] = $retorno;

So you are getting a table array with all user columns, you need to select the USER ID column

Try to do it this way...

$_SESSION['iduser'] = $retorno[ 'nomeDaColunaDoId' ];

You are unable to insert the USER ID because you are not receiving it, try to change your line, and add to what I did. You’ll probably solve your problem.

  • Thank you very much, I managed to solve the problem

Browser other questions tagged

You are not signed in. Login or sign up in order to post.