I create a json structure with this php code:
<?php
include "../base.php";
$STH = $DBH->prepare("SELECT * FROM customers");
$STH->execute();
$result = $STH->fetchall(PDO::FETCH_ASSOC);
$rows = $STH->rowCount();
$jsontext = "{";
$jsontext .= "total: ".$rows.",";
$jsontext .= "page: 0,";
$jsontext .= "records: [";
foreach($result as $key => $inner_arr) {
$jsontext .= "{";
foreach($inner_arr as $field_name => $field_value) {
$jsontext .= "{$field_name}: {$field_value}, ";
}
$jsontext .= "},";
}
$jsontext .= "]";
$jsontext .= "}";
echo json_encode($jsontext);
?>
the main problem is this line $jsontext .= "{$field_name}: {$field_value}, ";
When I print the whole script with "echo" it works. But with $jsontext .=
it is not working and I receive only "null".
try using json_encode built in function
thank you to @Satya and @keune.
changing the last line from
echo json_encode($jsontext);
to
echo $jsontext;
solves the problem.
Try:
$STH = $DBH->prepare("SELECT * FROM customers");
$STH->execute();
$result = $STH->fetchall(PDO::FETCH_ASSOC);
$rows = $STH->rowCount();
$jsontext['total'] = $rows;
$jsontext['page'] = 0;
foreach($result as $key => $inner_arr) {
foreach($inner_arr as $field_name => $field_value) {
$jsontext['records'][][$field_name] = $field_value;
}
}
echo json_encode($jsontext);
?>
p. s. i didnt tested it.
Replace
json_encode($jsontext);
with
echo $jsontext;