0

I need some support with a personal project Im working on. I have a connected device which sends JSON data at a defined interval (every 1 min / 5 min/ 15 mins etc) to a specific IP address on port 8080.

The JSON that is sent is in following format:

{
"MeterSN": “1234”,
"Status": ###,
“Variable1”: “###”,
"Variable2”: “###”,
"Variable3”: ###
}

I have started building a PHP Rest API to process this data but am somehow not able to save the to mySQL.

Here is what I have so far:

meterdata.php

class MeterDataInput{
    private $conn;
    private $table_name = "meterdata";
    public $MeterSN;
    public $StatusA;
    public $Variable1;
    public $Variable2;
    public $Variable3;

    public function __construct($db){
        $this->conn = $db;
    }
}
function createMeterRecord(){

    $query = "INSERT INTO
                " . $this->table_name . "
            SET
                MeterSN=:MeterSN, Status=:Status, Variable1=:Variable1, Variable2=:Variable2, Variable3=:Variable3";
    // prepare query
    $stmt = $this->conn->prepare($query);
    // sanitize
    $this->MeterSN=htmlspecialchars(strip_tags($this->MeterSN));
    $this->Status=htmlspecialchars(strip_tags($this->Status));
    $this->Variable1=htmlspecialchars(strip_tags($this->Variable1));
    $this->Variable2=htmlspecialchars(strip_tags($this->Variable2));
    $this->Variable3=htmlspecialchars(strip_tags($this->Variable3));
    // bind values
    $stmt->bindParam(":MeterSN", $this->MeterSN);
    $stmt->bindParam(":Status", $this->Status);
    $stmt->bindParam(":Variable1", $this->Variable1);
    $stmt->bindParam(":Variable2", $this->Variable2);
    $stmt->bindParam(":Variable3", $this->Variable3);
    // execute query
    if($stmt->execute()){
        return true;
    }
    return false;
}

index.php

// required headers
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");

// get database connection
include_once 'config/db.php';

// instantiate MeterData object
include_once 'objects/meterdata.php';

$database = new Database();
$db = $database->getConnection();

$meterdata = new MeterDataInput($db);

// get posted data
$data = json_decode(file_get_contents("php://input"));

// make sure data is not empty
if(!empty($data->MeterSN)){

    // set product property values
    $meterdata->MeterSN = $data->MeterSN;
    $meterdata->Status = $data->Status;
    $meterdata->Variable1 = $data->Variable1;
    $meterdata->Variable2 = $data->Variable2;
    $meterdata->Variable3 = $data->Variable3;

    // create the meter data entry
    if($meterdata->createMeterRecord()){
        // set response code - 201 created
        http_response_code(201);
        // update the status
        echo json_encode(array("message" => "Data record was added"));
    }
    // if unable to create the record
    else{

        // set response code - 503 service unavailable
        http_response_code(503);

        // tell the user
        echo json_encode(array("message" => "Unable to add record."));
    }
}

// data is incomplete
else{

    // set response code - 400 bad request
    http_response_code(400);

    // tell the user
    echo json_encode(array("message" => "Unable to create data record. Data is incomplete."));
}

Obviously i also have config.php and db.php

I am not sure where i am going wrong, however I am not able to see the records popupate within mySQL.

  • It's not clear exactly what the issue is. You say the incoming data is saved to a database. Then later you say need to save it to a database... . You mean you need to save it to a new or different database, or what? What do you mean "build a listener"...are you wanting to intercept the data sent to that "pushdata" URL. Is that not a server you can access or modify? Can't you just read the data that is already being saved into that mysql database? I think you need to give us a better idea of what the situation is exactly. – ADyson May 01 '19 at 10:51
  • Ok sorry for the light description... I have now taken this a bit further... and will post additional details – user3375834 May 01 '19 at 12:08
  • Side point: I actually don't think you need all those "required headers" since the device will not be making an AJAX request (since it's not running from a browser) and therefore won't be subject to CORS restrictions. The only one you are likely to need is the content-type one (`header("Content-Type: application/json; charset=UTF-8");`) – ADyson May 01 '19 at 12:37
  • Side point: 503 is not an appropriate response to send when the database call fails. 503 means the whole server is dead. 500 (Internal Server Error) would be a more appropriate response. – ADyson May 01 '19 at 12:38
  • Side point: If you're going to send a 201 response back when the item is created, then you're supposed to either provide the JSON of the created data within the response body, or provide a "Location" header which points to a URL where the new data can be retrieved. See https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/201 – ADyson May 01 '19 at 12:40
  • Anyway, if you're "not sure where you're going wrong", you need to do some debugging. Firstly, what output do you actually get back from the script? Have you tested it using a tool such as PostMan, to see what response you get, when sending some sample data? – ADyson May 01 '19 at 12:41
  • Secondly, you need to narrow down the exact point of failure. Some suggestions: 1) Try getting the script to simple echo `$data` after you've tried to read it from the input, so you know it has read the data correctly. 2) Ensure PHP error logging is switched on so you can see any exceptions logged to the default log file. Check the log file after each run. See https://stackoverflow.com/a/46455375/5947043 for setup details. – ADyson May 01 '19 at 12:45
  • 3) Ensure PDO is set to throw exceptions by default whenever anything in the database code fails. See https://stackoverflow.com/a/32648423/5947043 for setup details. With these various steps you should get more detailed info about what the issue is and where in the code it is happening. – ADyson May 01 '19 at 12:45

0 Answers0