How do I get the Logged in user ID in the PHP session and play in a variable to insert?

Asked

Viewed 2,394 times

2

I need to get the user ID already logged in to play in an Insert query, because I will connect it to a Foreign Key Employee. I need to get this ID, only I’m not sure how to proceed and I’m beginner in php.

Login script:

<?php
SESSION_start();
include('conexao.php');

if (empty($_POST['usuario']) || empty($_POST['senha'])) {
    header("location: index.php");
    exit();
}

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

$query = "select * from funcionarios where login='{$usuario}' and senha = '{$senha}'";

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

$row = mysqli_num_rows($result);

$error = "Usuário ou Senha incorretos";

if ($row > 0) {
    $_SESSION['usuario'] = $usuario;
    $_SESSION['senha'] = $senha;
    header('Location: paginaConsulta.php');
    exit();
} else {
    unset ($_SESSION['usuario']);
    unset ($_SESSION['senha']);
    $_SESSION["invalido"] = $error;
    header("location: index.php");
}

Part of the Insert:

//Caso não ocorra nenhum erro, permita que os dados sejam inseridos no banco.
  if ($row == 0) {
    $link = conexao();

    $query = "insert into clientes(nome_cliente, cnpj)
    values('{$nome_cliente}', '{$cnpj}')";
    $result = mysqli_query($link, $query);

    //Recupero o id do cliente que acabou de ser inserido

    $idCliente = mysqli_insert_id($link);

      //Recupero o id do funcionaio que acabou de ser inserido

    $idFuncionario = $_SESSION["usuario"];

    $query2 = "insert into erros(tipo_erro,solucao,data_ocorrencia,sistema, Fk_Funcionarios, Fk_Clientes)
    values('{$nome_erro}', '{$solucao}', '{$data}', '{$sistema}', '{$idFuncionario}', '{$idCliente}')";
    $result2 = mysqli_query($link, $query2);
    }


  header('location: paginaConsulta.php');
}

How do I declare a new session to pull up the ID? I am sending the form via post, and the ID is in AUTO INCREMENT in the database.

I don’t know how to recover the logged-in user ID in the session so I can play in this $Idfuncionaio variable.

The part of idClients is working.

  • 1

    Possible duplicate of Grab user id by SESSION

  • What the function conexao does? If it returns a connection to the bank there is much that can improve the code.

  • I managed to solve, with the solution of the companions below. What I could improve in the code?

2 answers

2


if ($row > 0) {

    $dados_usuario = mysqli_fetch_assoc($result);

    $_SESSION['id_usuario'] = $dados_usuario['id'];
    $_SESSION['usuario'] = $usuario;
    $_SESSION['senha'] = $senha;
    header('Location: paginaConsulta.php');
    exit();
}

Modify your if to this above.

Obs1: to recover the id user then just access $_SESSION['id_usuario'].

Note: I am considering that the field id in your database is written exactly this way (lower case letters), if different, make the change in the code.

  • 1

    It worked! After being able to pull the id of the logged-in user in the session, I was able to solve my problem and play this session in another variable that will be requested by INSERT. Thank you!

1

Do the following:

//seu código...
$result = mysqli_query(conexao(), $query);
$arrayResutado = mysqli_fetch_assoc($result); //Vai te retornar um array, com os retornos do banco para o select que você fez, o qual provavelmente tem o id que vc precisa...
if ($row > 0) {
    $_SESSION['usuario'] = $usuario;
    $_SESSION['senha'] = $senha;
    $_SESSION['usuario_id'] = $arrayResultado['usuario_id']; // Dentro das [''] você coloca identico ao campo no banco de dados;
    header('Location: paginaConsulta.php');
    exit();
} else {
    unset ($_SESSION['usuario']);
    unset ($_SESSION['senha']);
    $_SESSION["invalido"] = $error;
    header("location: index.php");
}
  • I managed to solve it. I wrote down your study solution.

Browser other questions tagged

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