FranzHuber23 FranzHuber23 - 1 year ago 103
PHP Question

Return JSON in php from mySql Database

I have the following data in my database:


I want to have the date in the JSON format below:

"labels": ["12.11.2016", "13.11.2016", "14.11.2016", ...],
"temperature": ["12", "35", "27", ...],
"humidity": ["56", "70", "87", ...]

My current code is:

$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_CASE, PDO::CASE_UPPER);

//Select the requested data
$sql = "SELECT date, temperature, humidity FROM `TestData` ORDER BY date ASC ";

$statement = $conn->prepare($sql);
$result = $statement->fetchAll(PDO::FETCH_ASSOC);

//Values returned for JavaScript
$labels = array();
$temperature = array();
$humidity = array();
$data = array();

foreach ($result as $row)
array_push($labels, $row['date'] );
array_push($temperature, $row['temperature']);
array_push($humidity, $row['humidity']);
$result = null;

//Load data in one single array
$data['labels'] = $labels;
$data['temperature'] = $temperature;
$data['humidity'] = $humidity;
//echo $data;
//echo json_encode($labels , JSON_FORCE_OBJECT);
echo json_encode($data);

but this gives me only the following sh*t:

Does anyone have an idea here? I just can't get it working even if I already searched the internet for like 5 hours :/

Answer Source


array_push($labels, $row['DATE'] );
array_push($temperature, $row['TEMPERATURE']);
array_push($humidity, $row['HUMIDITY']);

Looks like all you column names are upper case.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download