I'm trying to write a PHP code used to save temperature data and timestamp in a database and show the value in a table. The temperature data is sent to database by using an http post.
here the code:
index.php (display the table)
<?php
include("connect.php");
$link=Connection();
$sql="SELECT * FROM `temptrac_temp` ORDER BY `timestamp` DESC";
$result=mysqli_query($link, $sql);
/* determine number of rows result set */
$row_cnt = $result->num_rows;
printf("Result set has %d rows.\n", $row_cnt);
?>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Arduino thermometer control panel</title>
<link rel="stylesheet" href="./css/index.css?v=1.0">
</head>
<body>
<div class="container">
<p>Temperature Arduino checker</p>
<p>The temperature is:</p>
<table class="normal" border="2" cellspacing="1" cellpadding="1">
<tr>
<td> Temperature </td>
<td> Timestamp </td>
<td> Status </td>
</tr>
<?php
if($result!==FALSE){
while($row = mysqli_fetch_array($result)) {
if($row["temp"] <= 8){
printf("<tr><td> %s</td><td> %s </td><td> Ok! </td></tr>",
$row["temp"], $row["timestamp"]);
}
if($row["temp"] > 8){
printf("<tr><td> %s</td><td> %s </td><td> Alert! </td></tr>",
$row["temp"], $row["timestamp"]);
}
}
mysqli_free_result($result);
mysqli_close($link);
}else{
printf("there is an error");
}
?>
</table>
</div>
</body>
</html>
connect.php (connection to mysql server)
<?php
function Connection(){
/* php site version doesn't like so much "", prefer '' */
$mysqli = new mysqli('localhost', 'temptrac_temp', 'temptrac_temp2846', 'temptrac_temp');
/* check connection */
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
/* fuck maaan! check the function name return*/
return $mysqli;
}
?>
add.php (write a new row in the database)
<?php
include("connect.php");
$link = Connection();
$temp = mysqli_real_escape_string($_POST["temp"]);
//$lat =$_POST["lat"];
//$lng =$_POST["lng"];
$sql = "INSERT INTO temptrac_temp (ID, temp, timestamp) VALUES (NULL, temp=?, CURRENT_TIMESTAMP)";
$stmt = $link->prepare($sql);
$stmt->bind_param("d", $temp);
$stmt->execute();
//mysqli_query($link, $query);
$stmt->close();
$link->close();
header("Location: index.php");
exit();
?>
I'm doing http post with https://www.hurl.it/
In the page response I see always (empty) instead to see the code of the index page like the connection is not closed.
I was able to write a new row in the database only one time, so is like sometimes work some other no.... that's weird.
header("Location: index.php");
is the last line and is followed by
exit();
so all the procedure should works.
here the screenshot of the http post
To prevent SQL Injection I followed this video https://youtu.be/sJdWuPHKRRY?t=11m1s. Is not clear to me how to use the bind function. here I see "uid=?" and not only "?". How to include my $temp variable that is dynamic in my sql query in a proper way?
tnx so much!