0

Hi i have a table with name Users that have these columns:

UserId INT
DisplayName VARCHAR(50)
Username VARCHAR(50)
Password VARCHAR(50)

i get records from this table with mysqli (mysqli_query,mysqli_fetch_array) like this:

$users=array();
while($user=mysqli_fetch_array($result)
$users=array("User"=>$user);
echo json_encode(array("Users"=>$users));

and the result of json_encode is:

{"users":{
    "user":{
        "0":"1",
        "UserId":"1",
        "1":"name",
        "DisplayName":"name",
        "2":"usernameTest",
        "Username":"usernameTest",
        "3":"passwordTest",
        "Password":"passwordTest"
    }
}}

But must be:

{"users":{
    "user":{
        "UserId":"1",
        "DisplayName":"name",
        "Username":"usernameTest",
        "Password":"passwordTest"
    }
}}

2 Answers 2

3

Either tell mysql_fetch_array to fetch an associative array with MYSQLI_ASSOC:

$user = mysql_fetch_array($result, MYSQLI_ASSOC);

Or use mysqli_fetch_assoc that fetches an associative array:

$user = mysqli_fetch_assoc($result);
Sign up to request clarification or add additional context in comments.

Comments

2

Use mysqli_fetch_assoc():

$users=array();
while($user=mysqli_fetch_assoc($result)
  $users=array("User"=>$user);
echo json_encode(array("Users"=>$users));

Btw your code seems a little off. Are your sure you only want to have a single user in this format returned?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.