I'm trying to send some Json formatted data via POST from a micropython controller to a PHP page and then into a mySQL database. The problem I am having is that the PHP code is not reading in the values from the Json data and therefore it is not being inserted into the database.
At the moment, it seems like the data is being successfully sent to the PHP page and in the right format. Here is the code below:
Python code sending the data to the php page:
data = '{"DeviceName": 1, "Humidity": %.2f, "Temperature": %.2f }'%(hum,temp)
headers = {'content-type': 'application/json'}
print(data)
res = urequests.post('http://192.168.1.187/insert.php', json=data, headers=headers)
print(res)
Here is the JSON string being sent:
{"DeviceName": 1, "Humidity": 36.88, "Temperature": 27.99 }
PHP code:
$server = "localhost";
$username = "admin";
$password = "passw";
$db = "test";
$dbCon = new mysqli($server, $username, $password, $db) or die("Unable to Connect");
$response = array();
$res=array();
$jsonRaw = file_get_contents('php://input');
$json = json_decode($jsonRaw);
if($json!=null){
$temperature = $json->Temperature;
$device = $json->DeviceName;
$sql = "insert into hostdata (HostID, DandT, Temp) values ('$device', now(), '$temperature')";
if(mysqli_query($dbCon, $sql)){
$svrResp["code"] = "1";
$svrResp["message"] = "Sucessfully Connected";
echo json_encode($response);
}else{
$svrResp["code"] = "2";
$svrResp["message"] = mysqli_error($dbCon);
echo json_encode($response);
}
}else{
echo "JSON data error";
}
mysqli_close($dbCon);
?>
This should insert the deviceName (is actually a number) and the temperature value into the sql statement and update the database. However, it is triggering the sql insert statement, just both the HostID and Temperature values are 0 when it is inserted. Am I missing something?
Any help would be appreciated!!