Raspberry Pi output to a PHP webpage - php

Hi i have been tasked to do a online counter using passive infrared sensor and a Raspberry PI. I need to be able to post the count on a webpage page which i had to create on my own.However, i am unable to get the counter output which i had coded in python to my webpage page.
I have tried using count(output),exec() and shell_exec() and it did not work.
Is it possible not to try to use flask? As i am very new to webpage designing and python.
I am not very good in coding python or php.
These is the python codes i have written
import RPi.GPIO as GPIO #1
import math
import os
import threading
import subprocess
import time
import os.path
import MySQLdb
db = MySQLdb.connect(host="localhost", user="root", passwd="brandon",
db="menagerie")
cur =db.cursor()
GPIO.setmode(GPIO.BOARD)
GPIO.setup(12,GPIO.IN)
GPIO.setup(11,GPIO.IN) #16
peoplecount=0 #18
while(1):
if GPIO.input(12):
time.sleep(2)
peoplecount = peoplecount+1
time.sleep(1.5)
cur.execute("INSERT INTO people(vistor,Date) VALUES(1,now())")
db.commit()
print peoplecount
print "hello" #30
if(peoplecount < 1):
peoplecount=0
elif GPIO.input(11):
time.sleep(2)
peoplecount = peoplecount-1
time.sleep(1.5)
print peoplecount
print "come back again"
conn.commit()
cur.close()
These are my webpage codes :
<!DOCTYPE html>
<html>
<head>
<style>
table,th,td {
border:1px solid black;
}
</style>
</head>
<body>
<?php
echo "welcome to PI LAB<br>";
echo date ('y-m-d H:i:s');
$conn = new mysqli("localhost","root","brandon","menagerie");
if($conn->connect_error)
{
die("connection failed:" . $conn->connect_error);
}
$sql = "SELECT * FROM people";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "<table><tr><th>Vistor</th><th>Entry</th></tr>";
while($row = $result->fetch_assoc()) {
echo "<tr><td>" . $row["vistor"]. " </td><td> " . $row["Date"]. "</td>
</tr>";
}
echo"</table>";
}
$conn->close();
?>
</body>
</html>

I'm not sure I quite understand what you want, but if you just want a total visitor count, and you have one row in your table per visitor:
<!DOCTYPE html>
<html>
<head>
<style>
table,th,td {
border:1px solid black;
}
</style>
</head>
<body>
<?php
$conn = new mysqli("localhost","root","brandon","menagerie");
if($conn->connect_error)
{
die("connection failed:" . $conn->connect_error);
}
echo "welcome to PI LAB<br>";
echo date('y-m-d H:i:s');
$sql = "SELECT * FROM people";
$result = $conn->query($sql);
echo "Total visitors: ", $result->num_rows;
if ($result->num_rows > 0) {
echo "<table><tr><th>Vistor</th><th>Entry</th></tr>";
while($row = $result->fetch_assoc()) {
echo "<tr><td>" . $row["vistor"] . " </td><td> " . $row["Date"]. "</td></tr>";
}
echo"</table>";
}
$conn->close();
?>
</body>
</html>

Related

How to fetch data from php to html

Good Day! i would like to know on how to fetch data from php to html. I'm newbie with this kind of code can you help me? Here is my codes.
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://unpkg.com/leaflet#1.6.0/dist/leaflet.css" />
<script src="https://unpkg.com/leaflet#1.6.0/dist/leaflet.js"></script>
<style>
#map {position: absolute; top: 0; bottom: 0; left: 0; right: 0;}
</style>
</head>
<body>
<?php
$mysql_hostname = "localhost";
$mysql_username = "root";
$mysql_password = "root";
$mysql_database = "dtable";
$conn= mysqli_connect($mysql_hostname,$mysql_username,$mysql_password,$mysql_database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, Longitude, Latitude FROM androidtable where Emp_ID = '212' order by Date_log desc";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr><td>" . $row["id"]. "</td><td>" . $row["Longitude"] . "</td><td>"
. $row["Latitude"]. "</td></tr>";
}
echo "</table>";
} else { echo "0 results"; }
$conn->close();
?>
<div id = "map"></div>
<script>
var map = L.map('map').setView([7.1309155, 125.6402975], 13);
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '© OpenStreetMap contributors'
}).addTo(map);
L.marker([7.1309155, 125.6402975]).addTo(map)
.bindPopup('Employee 212 Location.<br> RealTime Tracker.')
.openPopup();
</script>
</body>
</html>
instead of this var map = L.map('map').setView([7.1309155, 125.6402975], 13); to this var map = L.map('map').setView([$row["Latitude"], $row["Longitude"]], 13);. I was hoping that you can help me with this problem.
You use JavaScript on your code so you can not directly do what you want with JavaScript and PHP. You may use AJAX to do this.
Here is a close question: How do I pass variables and data from PHP to JavaScript?
You can use this link, have a nice day.
You can echo out the array inside <script></script> like this
var ar = <?php echo json_encode($ar) ?>; <br>
then use loop to set the map

How to update table from postgresql database after specefic time interval using AJAX and PhP

I am using the technique done in this question. How to put data from database table to a html table using ajax and php.
Goal of my task is: update table from postgresql database after specific time interval lets say, after 1 minute. I want to use Ajax because I don't want that client referesh page. It should be done automatically. Before apply ajax, my code is in:
estat hardware.php file
<!DOCTYPE html>
<html>
<head>
<style> <?php include './../css/estat_hardware.css'; ?> </style>
</head>
<?php
$host = "10.80.145.98";
$port ="5432";
$user = "postgres";
$pass = "AIRFI2014";
$db = "hospital";
?>
<body>
<div class="maindiv">
<div id="tagstable">
<h3>Estat Tags</h3>
<?php
$con = pg_connect("host=$host dbname=$db user=$user password=$pass") or die ("Could not connect to server\n");
$query = "SELECT * FROM beacon";
$result = pg_query($con, $query) or die("Cannot execute query: $query\n");
$i = 0;
echo '<html><body><table>';
echo '<th>' . "TAG" . '</td>';
echo '<th>' . "BATERIA" . '</td>';
echo '<th>' . " VIST ÚLTIMA COP " . '</td>';
echo '<th>' . "ESTAT" . '</td>';
$i = 0;
while ($row = pg_fetch_array($result)){
$estat="TODO";
echo "<tr>";
echo "<td>".$row[1]."</td>";
echo "<td>".$row[3]."</td>";
echo "<td>".$row[2]."</td>";
echo "<td>".$estat."</td>";
echo "</tr>";
}
pg_free_result($result);
echo '</table></body></html>';
pg_close($con);
?>
</div>
</div>
</body>
</html>
I want to update the same table using AJAX. So, I studied about ajax and coded the mechanism in which there will be a call to server function, the server will get data from database and resturn it using json.The server file is: estat_hardware_server.php
<?php
$host = "10.80.145.98";
$port ="5432";
$user = "postgres";
$pass = "AIRFI2014";
$db = "hospital";
$con = pg_connect("host=$host dbname=$db user=$user password=$pass") or die ("Could not connect to server\n");
$query = "SELECT mac,ts,battery FROM beacon";
$result = pg_query($con, $query) or die("Cannot execute query: $query\n");
if(pg_num_rows($result)){
$data=array();
while($row=pg_fetch_array($result)){
$data[] = array(
'mac'=>$row['mac'],
'ts' =>$row['ts'],
'battery'=>$row['battery']
);
}
echo json_encode($data);
pg_free_result($result);
pg_close($con);
}
?>
On client side, I have the following code which should be updated from the ajax.
<!DOCTYPE html>
<html>
<head>
<style> <?php include './../css/estat_hardware.css'; ?> </style>
</head>
<body>
<div class="maindiv">
<div id="tagstable">
<h3>Estat Tags</h3>
<?php
echo '<html><body><table>';
echo '<th>' . "TAG" . '</td>';
echo '<th>' . "BATERIA" . '</td>';
echo '<th>' . " VIST ÚLTIMA COP " . '</td>';
echo '<th>' . "ESTAT" . '</td>';
echo '</table></body></html>';
?>
</div>
</div>
</body>
</html>
My ajax code which I tested on client side for correctly receiving data from json is:
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myObj = JSON.parse(this.responseText);
for (i = 0; i < myObj.length; i++) {
// I need to update the table here, after time interval 1 minute.
}
}
};
xmlhttp.open("GET", "pages/estat_hardware_server.php", true);
xmlhttp.send();
put ajax method into a function, call that function every 1 minute.
<script>
setInterval(function() {
UpdateHTMLTable();
}, 60000); // 60000 millisecond(60 second)
function UpdateHTMLTable(){
//ajax code here
}
</script>

Load MySQL data

I have MySQL server installed and I have created a test database named "test" and done a simple login example, with the ID, username, password and email. According to W3Schools, I have modified the code they provide:
<!DOCTYPE html>
<html>
<head>
<style>
table, th, td {
border: 1px solid black;
}
</style>
</head>
<body>
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, username, password, email FROM user";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "<table><tr><th>ID</th><th>Username</th><th>Password</th><th>Email</th></tr>";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr><td>" . $row["id"]. "</td><td>" . $row["username"]. "</td><td>" . $row["password"]. "</td><td>" . $row["email"]. "</td></tr>";
}
echo "</table>";
} else {
echo "0 results";
}
$conn->close();
?>
</body>
</html>
I've searched the directory of the database and I see in C:\Program Files\MySQL\MySQL Server 5.6\data a folder named "test" that contains 3 files, a .opt file, a .frm and a .ibd.
My question is, where should I put the html file in order to load this database data? Or should I change something from my code? Thanks!

PHP Oracle display result

i have a problem displaying the result of a SQL query (against Oracle DB). My web page code is below. I am using tnsnames and run the webserver and the page on the oracle db server itself. Running the query in sqlplus/sql developer works fine.
TNSNAMES:
testdb =
(DESCRIPTION =
(ADDRESS = (PROTOCOL = TCP)(HOST = 10.10.10.101)(PORT = 1521))
(CONNECT_DATA =
(SERVER = DEDICATED)
(SERVICE_NAME = testdb)
)
)
The page displays the 2 variables and afterwards directly the footer.
How can i display the returned data? Can somebody please help me?
Thanks
<head>
<title>Reports</title>
<link href="Site.css" rel="stylesheet">
</head>
<body>
<?php include("Header.php"); ?>
<div id="main">
<h1>Report1</h1>
<h2>Report2</h2>
<p>Report3</p>
<?php
if (isset($_GET['var1'])) {
$var_storenr = $_GET['var1'];
}
if (isset($_GET['var2'])) {
$var_storearea = $_GET['var2'];
}
echo "<p>Var 1: " . $var_storenr . "</p>";
echo "<p>Var 2: " . $var_storearea . "</p>";
$db_user='testusr';
$db_pass='testusr';
$db_name='testdb';
$conn = oci_connect($db_user, $db_pass, $db_name);
$query = 'select id_store, store_des from np_stores where id_store in ('.$var_storenr.') and id_region = '.$var_storearea.';';
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}
$stid = oci_parse($conn, $query);
oci_execute($stid);
echo "<table border='1'>\n";
while ($row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS)) {
echo "<tr>\n";
foreach ($row as $item) {
echo " <td>" . ($item !== null ? htmlentities($item, ENT_QUOTES) : " ") . "</td>\n";
}
echo "</tr>\n";
}
echo "</table>\n";
?>
<?php include("Footer.php"); ?>
</div>
</body>
i have figured it out. It was a problem with the oracle connection, mainly PHP and x64 Oracle client.
installed x32 client and works fine.
Thanks,

Calculate columns from database then pull into table cell

EDIT: I have successfully been able to calculate the value I was trying to get, but instead of calculating that value for each row, it is just calculating it once and posting that value everywhere. How do I make it recalculate for each row using the code I have?
Picture: http://img515.imageshack.us/img515/9064/example2w.png
New Code:
<html>
<head>
<title>PHP-MySQL Project 4</title>
<div align="center">
<p>
PHP-MySQL Project 4
<br/>
By: Ryan Strouse
</p>
</div>
</head>
<body bgcolor="#99FFFF">
<?php
$DBName = "surveys";
$DBConnect = #mysqli_connect("localhost", "students", "password")
Or die("<p>Unable to connect to the database server.</p>"
. "<p>Error code " . mysqli_connect_errno()
. ": " . mysqli_connect_error()) . "</p>";
if (!$DBConnect)
{
echo "<p> The database server is not available.</p>";
}
else
{
echo "<p> Successfully connected to the database $DBName</p>";
}
mysqli_select_db($DBConnect, $DBName);
echo "<p>Database -'$DBName'- found</p>";
$SQLstring = "SELECT * FROM surveys WHERE surveyCode = 'GEI001'";
$QueryResult = #mysqli_query($DBConnect, $SQLstring);
echo $SQLstring;
$row = mysqli_fetch_assoc($QueryResult);
$count_surveys = $row['surveyResponses'];
echo "<p>Total Responses: $count_surveys</p>";
$SQLstring2 = "SELECT * FROM results WHERE surveyCode = 'GEI001'";
$QueryResult2 = #mysqli_query($DBConnect, $SQLstring2);
echo $SQLstring2;
echo "<br/>";
$Row = mysqli_fetch_assoc($QueryResult2);
$SQLstring3 = "SELECT * FROM surveys, results";
$QueryResult3 = #mysqli_query($DBConnect, $SQLstring3);
$fetchrow = mysqli_fetch_assoc($QueryResult3);
$result_amount = (($fetchrow['resultResponses'] / $fetchrow['surveyResponses']) * 100);
echo "<table>";
echo "<tr><th>Commercial</th> <th>Views</th> <th>Percentage</th></tr>";
do {
echo "<tr><td>{$Row['resultDescription']}</td>";
echo "<td>{$Row['resultResponses']}</td>";
echo "<td>$result_amount</td></tr>";
$Row = mysqli_fetch_assoc($QueryResult3);
} while ($Row);
echo "</table>";
?>
<center>
<h3>Return To Main Page</h3>
<h3>Return to Menu</h3>
</center>
</body>
<footer>
<div align="center">
© Copyright Ryan Strouse ©
</div>
</footer>
</html>
I have two database tables and I am successfully pulling in column data into a table. The third cell of the table I would like to calculate a percentage out of some of the columns from the database. I'm not sure how to code this... I've tried to come up with something in the SELECT statement from another thread I found with no luck.
Here is a picture of the query I'm trying to get to work: http://img696.imageshack.us/img696/3862/examplegw.png
<html>
<head>
<title>PHP-MySQL Project 4</title>
</head>
<body bgcolor="#99FFFF">
<?php
$DBName = "surveys";
$DBConnect = #mysqli_connect("localhost", "students", "password")
Or die("<p>Unable to connect to the database server.</p>"
. "<p>Error code " . mysqli_connect_errno()
. ": " . mysqli_connect_error()) . "</p>";
if (!$DBConnect)
{
echo "<p> The database server is not available.</p>";
}
else
{
echo "<p> Successfully connected to the database $DBName</p>";
}
mysqli_select_db($DBConnect, $DBName);
echo "<p>Database -'$DBName'- found</p>";
$SQLstring = "SELECT * FROM surveys WHERE surveyCode = 'GEI001'";
$QueryResult = #mysqli_query($DBConnect, $SQLstring);
echo $SQLstring;
$row = mysqli_fetch_assoc($QueryResult);
$count_surveys = $row['surveyResponses'];
echo "<p>Total Responses: $count_surveys</p>";
$SQLstring2 = "SELECT * FROM results WHERE surveyCode = 'GEI001'";
$QueryResult2 = #mysqli_query($DBConnect, $SQLstring2);
echo $SQLstring2;
echo "<br/>";
$Row = mysqli_fetch_assoc($QueryResult2);
//this is where I am trying to calculate the value and then below it display in table
//cell # 3
$SQLstring3 = "SELECT *,((resultResponses/surveyResponses)*100) AS AMOUNT FROM surveys, results";
$QueryResult3 = #mysqli_query($DBConnect, $SQLstring3);
do {
echo "<table>";
echo "<tr><th>Commercial</th> <th>Views</th> <th>Percentage</th></tr>";
echo "<tr><td>{$Row['resultDescription']}</td>";
echo "<td>{$Row['resultResponses']}</td>";
echo "<td>$QueryResult3</td></tr>";
$Row = mysqli_fetch_assoc($QueryResult);
} while ($Row);
echo "</table>";
?>
<center>
<h3>Return To Main Page</h3>
<h3>Return to Menu</h3>
</center>
</body>
<footer>
</footer>
</html>
IF I understand what you are asking, you're trying probably to calculate the percentage of a value that you can find in a MySQL query's results. If that is so, then I'd use the function mysql_num_rows to get the total of the records and then in a while and if I'd have a counter of how many times I meet that value.
Then you just do simple math, for example:
result = (100 * counter) / mysql_num_rows
and have a percentage. Then you just echo the result wherever you want! :)
I hope I have understood your question correctly!
$result = mysql_query("SELECT yourRow FROM yourTable");
$aArray = array();
$cont=0;
while($col = mysql_fetch_assoc($result){
$aArray[$cont] = $col['yourRow'];
cont++;
}
That should give you a workable array for you to make your math with it and then echo it. Cheers

Categories