What best practices should be followed when integrating PHP with HTML to retrieve and store data from a smart meter?

When integrating PHP with HTML to retrieve and store data from a smart meter, it is important to securely handle the data transmission and storage. Use PHP to create a secure connection to the smart meter's API, retrieve the data, and store it in a database. Ensure that the PHP code is properly sanitized to prevent SQL injection attacks and validate the data before storing it.

<?php
// Connect to the smart meter API
$api_url = 'https://smartmeter-api.com/data';
$api_key = 'your_api_key';
$data = file_get_contents($api_url . '?api_key=' . $api_key);

// Store the retrieved data in a database
$servername = 'localhost';
$username = 'username';
$password = 'password';
$dbname = 'smart_meter_data';

$conn = new mysqli($servername, $username, $password, $dbname);

if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Sanitize and validate the data before storing it
$data = $conn->real_escape_string($data);

$sql = "INSERT INTO meter_data (data) VALUES ('$data')";

if ($conn->query($sql) === TRUE) {
    echo "Data stored successfully";
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}

$conn->close();
?>