How to fetch data from php to html - php

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

Related

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>

Update the contents of table rather then complete table using ajax and PhP

I am beginner in the PhP and Jquery. So, may be the solution to this question will be easy. I am successfully updating table using ajax and PhP. The issue is that table is updated by removing the all the data, and then populating new data.
I am looking for any other approach. After getting new data through PhP, compare new data with old data,...if there is some issue in hardware, then change the status..also keep the time from which the hardware stopped working. I ask question before Put data from Postgresql database to table using Ajax and PhP, in which #Mcsky suggested me a solution, but I did not get his approach. So, How to update table data only?, instead of complete refresh of table, which feels like page refresh. here is my client code: estat_hardware.php
<!DOCTYPE html>
<html>
<head>
<style> <?php include './../css/estat_hardware.css'; ?> </style>
</head>
<body>
<div class="maindiv">
<div id="tagsDiv">
<h3>Estat Tags</h3>
<?php
echo '<table id="tags_table">';
echo "<thead>";
echo "<tr>";
echo '<th>' . "TAG" . '</th>';
echo '<th>' . "BATERIA" . '</th>';
echo '<th>' . " VIST ÚLTIMA COP " . '</th>';
echo '<th>' . "ESTAT" . '</th>';
echo "</tr>";
echo "</thead>";
echo "<tbody>";
echo "</tbody>";
echo '</table>';
?>
</div>
</div>
<script src='http://code.jquery.com/jquery-3.1.1.min.js'></script>
<script>
$(document).ready(function(){
UpdateHTMLTable();
setInterval(function() {
UpdateHTMLTable();
}, 5000); // 5000 millisecond(5 second)
function UpdateHTMLTable(){
/* $('#tags_table tbody').empty(); */
$('#tags_table tbody').html("");
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
data = JSON.parse(this.responseText);
for (i = 0; i < data.length; i++) {
console.log(data[i]);
var row = $("<tr />");
$("<td />").text(data[i].mac).appendTo(row);
$("<td />").text(data[i].battery).appendTo(row);
$("<td />").text(data[i].ts).appendTo(row);
$battery_beacon=data[i].battery;
if($battery_beacon<15)
{
$status="Canvi Batteria";
}
else{
$status="Correcte ";
}
$("<td />").text($status).appendTo(row);
row.appendTo('#tags_table');
}
}
};
xmlhttp.open("GET", "pages/estat_hardware_server.php", true);
xmlhttp.send();
}
});
</script>
</body>
</html>
Server code is:
<?php
header("Content-Type: application/json; charset=UTF-8");
$host = ip";
$port ="portNumber";
$user = "abc";
$pass = "....";
$db = "name";
$con = pg_connect("host=$host dbname=$db user=$user password=$pass")
or die ("Could not connect to server\n");
$query = "query string for database";
$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);
}
?>

Raspberry Pi output to a PHP webpage

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>

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!

Transferring DB data between PHP and Javascript 2D array

I am attempting to get all the data from a MySQL db with PHP, initialise a 2D java array and populate it with the PHP data.
I am having trouble embedding JS in the PHP. I have marked up what is working and what isn't.
As you will see, some of the embedded java works but not all.
Any thoughts?
<body>
<?php
$con = mysql_connect("XXXXXX.COM","guest","password");
mysql_select_db("HHG", $con);
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
else
{
$result = mysql_query("SELECT * FROM articles", $con);
$numrows = mysql_num_rows($result);
echo "DB connection OK <br/>";
echo "Found ";
echo $numrows;
echo " records <br/><br/>";
} // EVERYTHING WORKS UP TO HERE
?>
<script type="text/javascript">
document.write("THIS IS THE FISRT JS DOING SOMETHING"); // THIS DOES NOTHING
numrows = <?php echo $numrows; ?>; // THIS DOES NOTHING
string [][] hhgdata = new string[numrows][4]; // THIS DOES NOTHING
document.write("Records = " + numrows + "<br/>"); // THIS DOES NOTHING
</script>
<?
$counter = 1;
while ($row = mysql_fetch_assoc($result))
{
echo $row["idimg"]; echo "<br/>"; //THIS WORKS
$hhgtitle = $row["hhgtitle"]; //THIS WORKS
echo $hhgtitle; echo "<br/>"; //THIS WORKS
?>
<script type="text/javascript"> //THIS WORKS
counter = <?php echo $counter; ?>; //THIS WORKS
document.write("counter = " + counter + "<br/><br/>"); //THIS WORKS
hhgtitle = <?php echo $hhgtitle; ?>; // THIS DOES NOTHING
document.write("Title: "); // THIS DOES NOTHING
hhgdata[counter][1]= hhgtitle; // THIS DOES NOTHING
document.write(hhgdata[counter][1]); // THIS DOES NOTHING
</script>
<?
$counter++; // THIS WORKS
}
?>
</body>
You are mixing up Java and JavaScript. For example this is Java syntax, you can't write this within a script tag which should only contain JavaScript:
string [][] hhgdata = new string[numrows][4];
The JavaScript arrays are dynamic, this should be enough:
var hhgdata = [];
When you want to add another array into it, as you seem to be doing later in your code, just do this:
hhgdata[counter] = [];
And then assign to the inner array:
hhgdata[counter][1] = hhgtitle;
You are also creating multiple assigning an unquoted string literal to variable with this (assuming $hhgtitle contains a string):
hhgtitle = <?php echo $hhgtitle; ?>;
It should be something like this:
hhgtitle = <?php echo '"' . $hhgtitle .'"'; ?>;
Finally, while it's not incorrect, your PHP while loop is creating multiple script elements in your HTML.
EDIT
I have made the changes described above as well as in comments, copy-paste exactly and see how it goes:
<body>
<?php
$con = mysql_connect("XXXXXX.COM","guest","password");
mysql_select_db("HHG", $con);
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
else
{
$result = mysql_query("SELECT * FROM articles", $con);
$numrows = mysql_num_rows($result);
echo "DB connection OK <br/>";
echo "Found ";
echo $numrows;
echo " records <br/><br/>";
} // EVERYTHING WORKS UP TO HERE
?>
<script type="text/javascript">
document.write("THIS IS THE FISRT JS DOING SOMETHING"); // THIS DOES NOTHING
numrows = <?php echo $numrows; ?>; // THIS DOES NOTHING
var hhgdata = new Array(numrows); // THIS DOES NOTHING
document.write("Records = " + numrows + "<br/>"); // THIS DOES NOTHING
</script>
<?php
$counter = 1;
while ($row = mysql_fetch_assoc($result))
{
echo $row["idimg"]; echo "<br/>"; //THIS WORKS
$hhgtitle = $row["hhgtitle"]; //THIS WORKS
echo $hhgtitle; echo "<br/>"; //THIS WORKS
?>
<script type="text/javascript"> //THIS WORKS
var counter = <?php echo $counter; ?>; //THIS WORKS
document.write("counter = " + counter); //THIS WORKS
hhgtitle = <?php echo '"' . $hhgtitle . '"'; ?>; // THIS DOES NOTHING
document.write("Title: "); // THIS DOES NOTHING
hhgdata[counter] = [];
hhgdata[counter][1]= hhgtitle; // THIS DOES NOTHING
document.write("<br />hhgdata[counter][1]: " + hhgdata[counter][1]); // THIS DOES NOTHING
</script>
<?php
$counter++; // THIS WORKS
}
?>
</body>
Why not just take the PHP array of data and json_encode it? Then you can work with it in Javascript, see below:
var json = <?php echo json_encode($foo); ?>;
You can learn more about how to do this here: http://www.openjs.com/scripts/data/json_encode.php

Categories