0

Been looking at this for a while now, it seems simple enough but for some reason I am unable to grasp it.

My code at the moment outputs this:

{"society_id":1,"name":"TestName1","email":"Test@email1","description":"TestDes1"}
{"society_id":2,"name":"TestName2","email":"Test@email2","description":"TestDes2"}

But what I need is this:

[{"society_id":1,"name":"TestName1","email":"Test@email1","description":"TestDes1"},
{"society_id":2,"name":"TestName2","email":"Test@email2","description":"TestDes2"}]

Could somebody point me in the right direction please? I'm very new to PHP.

<?php

    $user = 'root';
    $pass = '';
    $db = 'uopuser';

    $con=mysqli_connect('localhost', $user, $pass, $db) or die('Unable to connect');


    $statement = mysqli_prepare($con, 'SELECT * FROM society');
    mysqli_stmt_execute($statement);

    mysqli_stmt_store_result($statement);
    mysqli_stmt_bind_result($statement, $society_id, $name, $email, $description);

$society = array();

while(mysqli_stmt_fetch($statement)){
    $society['society_id'] = $society_id;
    $society['name'] = $name;
    $society['email'] = $email;
    $society['description'] = $description;
    echo json_encode($society);
}

echo json_encode($society);

    mysqli_stmt_close($statement);

    mysqli_close($con);
?>

2 Answers 2

2

You need a two dimensional array. Essentially an "array of arrays."

See the examples here for more information.

$society = array();

while(mysqli_stmt_fetch($statement)){
    $society[] = array(
        'society_id'  = $society_id,
        'name'        = $name,
        'email'       = $email,
        'description' = $description
    );
}

echo json_encode($society);
Sign up to request clarification or add additional context in comments.

Comments

1

For your required json format you need to use multi dimensional array. And no need to use json_encode() inside the while() loop.

Example:

$society = array();
$key = 0;
while(mysqli_stmt_fetch($statement))
{ 
    $society[$key]['society_id'] = $society_id; 
    $society[$key]['name'] = $name;
    $society[$key]['email'] = $email;
    $society[$key]['description'] = $description; 
    $key++;
}
echo json_encode($society); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.