0

I want to output some records from mysql table with resCode and resText in JSON in the following way:

{ 
 "data":[ 
 { 
 "id":"44",
 "month":"January",
 "income":"2500",
 "expanse":"0"
 },
 { 
 "id":"45",
 "month":"February",
 "income":"5500",
 "expanse":"400"
 },
 { 
 "id":"47",
 "month":"March",
 "income":"25000",
 "expanse":"11000"
 }
 ],
 "resCode":"200",
 "resText":"SUCCESS"
}

Since I'm very new to PHP arrays, I'm unable to format the server side part to output like above. Also I don't know how to output the resCode and resText.

Any help for the same will be appreciated.

PHP part:

<?php
include_once 'includes/db_connect.php';
?>
<?php
$stmt = $mysqli->prepare("SELECT * FROM records");
 $stmt->execute(); // Execute the prepared query.
 $stmt->store_result();
 // get variables from result.
 $stmt->bind_result($id, $month, $income, $expanse);
 while ($stmt->fetch()) {
 $data[]=array(id=>$id, month=>$month, income=>$income, expanse=>$expanse);
 }
 $response["data"] = $data;
 $response["resCode"] = "200";
 echo json_encode($response);
?>
il_raffa
5,175145 gold badges35 silver badges41 bronze badges
asked Apr 9, 2017 at 12:11
2
  • Please also include what your code currently outputs Commented Apr 9, 2017 at 12:15
  • @SamiKuhmonen It gives error.. As I told you I don't know the correct way to output. Commented Apr 9, 2017 at 12:19

1 Answer 1

1
while ($stmt->fetch()) {
 $output["data"][]=array('id'=>$id, 'month'=>$month, 'income'=>$income, 'expanse'=>$expanse); 
}
$output["resCode"] = '200';
$output["resText"] = 'SUCCESS';
echo json_encode($output);
answered Apr 9, 2017 at 12:26
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.