How to return more than one property with JSON?

Asked

Viewed 117 times

0

I would like to know how I return more than one property in PHP. Below is the code where I return the user name and wanted to return, in addition, his registration. I tried to do the same by adding the 'license plate', but it didn’t work.

<?php
include('connect.php');
session_start();
if($_SESSION['logado']) {
    $nome = $_SESSION['nome'];
    //$matricula = $_SESSION['matricula'];
} 
echo json_encode(array('nomeUsuario' => $nome));
//'matricula' => $matricula));
?>
  • 2

    how did you try? Using echo json_encode(array('nomeUsuario' => $nome, 'matricula' => $matricula)); should work.

  • That, Oeslei. I tried that way.

  • Maybe your variable $_SESSION['matricula'] is empty? What response does the browser receive (see directly in the browser console)?

  • In the console is returned the name of the user right, but the registration appears null.

  • But does the right registration field appear? Have the value null does not mean that it is not working. As I said in the other comment, its variable $_SESSION['matricula'] must be empty.

  • The registration field appears, but in my database the registration field is not empty...

  • Put your command on echo in this way: echo json_encode($_SESSION); and analyze all fields of your Session. Even if the registration is correct in the database, maybe your script to set the Session has an error.

  • All the fields showed up except for the license plate..

  • gives a print_r to see if the license plate is on $_SESSION

  • The license plate didn’t show up on print_r,

  • If enrollment is non-existent in SESSION, then the hole is lower.. Look in the script that creates SESSION, because that’s where the problem should be..

Show 6 more comments

2 answers

1

Just add the data in the array, like this

echo json_encode(array(
    'nomeUsuario' => $nome,
    'outro_dado' => 'novo dado'
));
  • I did that, Beraldo. You can see up there that it is commented. However, it did not work.

0


As suggested to me, I took a look at the script where I start the session and realized that I was missing a line of code that delegated the registration.

if($array['login'] == $login){                
            if($array['password'] == $senha){
                $_SESSION['logado'] = true;
                $_SESSION['nome'] = $array['nome'];
                $_SESSION['login'] = $array['login'];
                $_SESSION['level'] = $array['level'];
                $_SESSION['matricula'] = $array['matricula']; //ESSA ERA A LINHA QUE FALTAVA
                ...
                ...
            }
}

Browser other questions tagged

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