Building Arduino Projects for the Internet of Things

(Steven Felgate) #1

CHAPTER 8 ■ IOT PATTERNS: WEB APPS


Receive and Store Sensor Data


As shown in Figure  8-7 , create a new file called add.php in the tempmonitor folder. This
script will perform two tasks—first it will fetch information from the HTTP request and
then it will insert this information as a new row in the database table.


Open the newly created file in a text editor and copy or type the code provided
in Listing 8-3. As mentioned in the previous step, in order to store data, a database
connection needs to be established. You created util-dbconn.php to perform that task,
so in this file you need to include util-dbconn.php. The util-dbconn.php file provides
access to the $mysqli variable, which contains connection references and will be used to
run the SQL queries.
The example in this book is hosted at http://bookapps.codifythings.com/
tempmonitor , and Arduino will be sending temperature data to add.php using an HTTP
GET method. As discussed in Chapter 2 , HTTP GET uses a query string to send request
data. So, the complete URL with the query string that Arduino will be using becomes
http://bookapps.codifythings.com/tempmonitor/add.php?temperature=79.5.
Your PHP code will need to extract temperature values from the query string using the
$_GET['temperature'] statement.
Now you need to store this temperature value in the database table as a new row.
Prepare an INSERT SQL statement in $sql variable. You just need to pass the temperature
value, as ID and TIMESTAMP are both auto-generated, so the database will take care of that
for you.
Finally, execute the INSERT SQL statement using $mysqli->query($sql) and check
the $result variable for success or failure.


Figure 8-7. File to receive and store data in add. php

Free download pdf