PHP - SQL Query

Asked

Viewed 60 times

0

I’m trying to implement a code to list information from 3 tables. I want to display on the screen only the data that was registered by the user id = '20'. This value '20' I’m taking from a session variable and I want to put in my product listing function but I’m not getting.

follow:

$idSessao = $_SESSION['sessaoId'];

function listaProdutos($conexao){
    $produtos = array();
    $resultado = mysqli_query($conexao, "select p.*, c.nome as categoria_nome, u.id as id_usuario from produtos as p inner join categorias as c on c.id = p.categoria_id inner join usuarios as u on u.id = p.usuario_id where p.usuario_id = 20");
    while ($produto = mysqli_fetch_assoc($resultado)){
        array_push($produtos, $produto);
    }
    return $produtos;
}

Where is p.usuario_id = 20 would like to do that p.usuario_id = {$idSessao} but he returns nothing.

  • 2

    Have you checked if you are able to recover the session value correctly? Have you tried printing the SQL code to see if it is correct? Usually doing tests of this kind if you get to the root of the problem.

  • The value of the variable was not entering the function, so it was blank. But the friend Rodrigo Sartori showed alternatives to take the value and put it within the function

1 answer

1


If code has a variable scope problem, $idThis is not a global variable, so the function does not "see" that variable. About scope of functions take a look here

To solve the problem, or you declare $idSease within the function(do not recommend).

global $idSessao

Or you put this line inside the function :

$idSessao = $_SESSION['sessaoId'];

or even put a parameter in the function in this way

$idSessao = $_SESSION['sessaoId'];

function listaProdutos($conexao,$usuario_id){
    $produtos = array();
    $resultado = mysqli_query($conexao, "select p.*, c.nome as categoria_nome, u.id as id_usuario from produtos as p inner join categorias as c on c.id = p.categoria_id inner join usuarios as u on u.id = p.usuario_id where p.usuario_id =".$usuario_id); // Corrigi o seu código aqui
    $produtos = mysqli_fetch_all($resultado); //não precisa de laço while se vai retornar um array 
    return $produtos;
}

//chamada da função
function listaProdutos($conexao,$idSessao);

This third option will give you greater flexibility in the function, since the id_user can come from anywhere, making the function more reusable. About mysqli_fetch_all you can read more here

  • I want to thank Rodrigo Sartori. I used the 3 alternative and it worked perfectly. Thanks!

Browser other questions tagged

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