I'm trying to get an Object from my file called load.php, I'm trying to get the information from load.php every 5s. For some reason, I could make one part of it, but I can't seem to get the other variable.
<script type="text/javascript" src="jquery-3.4.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function (){
setInterval(function () {
$.getJSON('load.php', function(sensors) {
if (sensors)
{
$('#p0-blocoCorrente').text(sensors.sensor1);
$('#p1-blocoCorrente').text(sensors.sensor2);
$('#p2-blocoCorrente').text(sensors.sensor3);
//Error here:
$('#p3-blocoCorrente').text(soma);
}
});
}, 5000);
});
</script>
This is my load.php file:
<?php
session_start();
include_once 'includes/dbh.inc.php';
$soma = 0;
$id = $_SESSION['userId'];
$dBname = "infosensor";
$conn = mysqli_connect($servername, $dBUsername, $dBPassword, $dBname);
$sql = "SELECT sensor1, sensor2, sensor3 FROM `$id` ORDER BY id DESC LIMIT 1;";
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_assoc($result);
$sensors = array();
if($row)
{
for ($i = 1; $i <= 3; $i++) {
$s1 = $row["sensor$i"];
$ss1 = intval($s1 * ($p = pow(10, 2))) / $p;
$soma += $row["sensor$i"];
$sensors["sensor$i"] = $ss1 . "A";
}
echo json_encode($sensors);
} else {
echo json_encode(null);
}
?>
In the PHP add soma to the array before json'ing it
<?php
session_start();
include_once 'includes/dbh.inc.php';
$soma = 0;
$id = $_SESSION['userId'];
$dBname = "infosensor";
$conn = mysqli_connect($servername, $dBUsername, $dBPassword, $dBname);
$sql = "SELECT sensor1, sensor2, sensor3 FROM `$id` ORDER BY id DESC LIMIT 1;";
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_assoc($result);
$sensors = array();
if($row) {
for ($i = 1; $i <= 3; $i++) {
$s1 = $row["sensor$i"];
$ss1 = intval($s1 * ($p = pow(10, 2))) / $p;
$soma += $row["sensor$i"];
$sensors["sensor$i"] = $ss1 . "A";
}
// add soma to the array
$sensors['soma'] = $soma;
echo json_encode($sensors);
} else {
echo json_encode(null);
}
?>
Then in the javascript, get it out to whereever you want to place it
<script type="text/javascript" src="jquery-3.4.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function (){
setInterval(function () {
$.getJSON('load.php', function(sensors) {
if (sensors) {
$('#p0-blocoCorrente').text(sensors.sensor1);
$('#p1-blocoCorrente').text(sensors.sensor2);
$('#p2-blocoCorrente').text(sensors.sensor3);
$('#p3-blocoCorrente').text(sensors.soma);
}
});
}, 5000);
});
</script>
Related
I am using a php file to pull data from a mysql database and then pushing it through to a html page using Ajax:
the data is being pulled in correctly and it looks to be pushed through as it shows in the network tab (response) but when i look in the console log there is nothing showing any ideas why
php
<?php
header('Content-type: application/json');
$servername = "test:3306";
$username = "test";
$password = "test!";
$dbname = "test";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
# header('Content-Type: applicaton/json');
$sql = "SELECT beacon,TIME_FORMAT(TIMEDIFF(max(`time`),min(`time`)), '%i.%s')
AS `delivery_avg`
FROM `test`.`test`
where date = CURDATE()
and time > now() - INTERVAL 30 MINUTE
group by beacon ";
$result = $conn->query($sql);
$sql2 = 'SELECT
*
FROM
(SELECT
beacon,location,date,
COUNT(location) AS counter
FROM `test`.`test`
WHERE `date` = CURDATE() and `time` > NOW() - interval 40 second
GROUP BY beacon) AS SubQueryTable
ORDER BY SubQueryTable.counter DESC;';
$result = $conn->query($sql2);
$result = mysqli_query($conn , $sql);
$rows = array();
while($r = mysqli_fetch_assoc($result)) {
$rows[] = $r;
}
echo json_encode($rows);
$result2 = mysqli_query($conn , $sql2);
$rows2 = array();
while($r = mysqli_fetch_assoc($result2)) {
$rows2[] = $r;
}
echo json_encode($rows2);
$conn->close();
?>
html
<script>
$(document).ready(function() {
for (var i = 0; i < 12; i++) {
var row = $('<tr>').appendTo("#zoning tbody");
for (var j = 1; j < 11; j++) {
$(`<td class='${i * 10 + j}'>${i * 10 + j}</td>`).appendTo(row);
}
}
$.get('php/test.php', function(response) {
console.log(response);
var row;
response.forEach(function(item, index) {
console.log(item.delivery_avg,item.beacon,item.location);
$(`td.${item.beacon}`).css('background-color', item.location).toggleClass('coloured');
});
});
function updateTable() {
//console.log('function called');
$('td.coloured').css('background-color','#8F8F8F').toggleClass('coloured');
$.get('php/test.php', function(response) {
response.forEach(function(item, index) {
console.log(item.delivery_avg,item.beacon,item.location);
//$('td.coloured').css('background-color','#8F8F8F').toggleClass('coloured');
$(`td.${item.beacon}`).css('background-color', item.location).toggleClass('coloured');
if (item.delivery_avg <= 10.00) {
return $(`td.${item.beacon}`).css({'border-color':'lime', 'border-width':'thick'}).toggleClass('coloured');
} else if (item.delivery_avg>= 10.01 && item.delivery_avg <= 20.00) {
return $(`td.${item.beacon}`).css({'border-color':'orange', 'border-width':'thick','background-color':item.location}).toggleClass('coloured');
} else if (item.delivery_avg>= 20.01 && item.delivery_avg <= 30.00) {
return $(`td.${item.beacon}`).css({'border-color':'pink', 'border-width':'thick','background-color':item.location}).toggleClass('coloured');
}
});
});
}
var updateTableInterval = setInterval(updateTable, 2000);
});
</script>
I have 2 files php: connect.php and getsp.php. As follow:
- Connect.php:
$host = "localhost";
$username = "root";
$password = "";
$database = "thietbi";
$conn = mysqli_connect($host, $username, $password, $database);
mysqli_query($conn, "SET NAMES 'uft8'");
- Getsp.php
include "connect.php";
// mysqli_set_charset($conn, "utf8");
$page = $_GET['page'];
$idsp = 1;
$space = 5;
$limit = ($page - 1) * $space;
$mangsanpham = array();
$query = "SELECT * FROM sanpham WHERE idsanpham = $idsp LIMIT $limit,$space";
$data = mysqli_query($conn,$query);
while ($row = mysqli_fetch_assoc($data)) {
$id = $row['id'];
$tsp = $row['tensanpham'];
$gsp = $row['giasanpham'];
$hsp = $row['hinhanhsanpham'];
$mtsp = $row['motasanpham'];
$isp = $row['idsanpham']));
array_push($mangsanpham, new Sanpham($id, $tsp, $gsp, $hsp, $mtsp, $isp));
}
echo json_encode($mangsanpham);
class Sanpham{
function Sanpham($id, $tensp, $giasp, $hinhsp, $motasp, $idsanpham){
$this->id = $id;
$this->tensp = $tensp;
$this->giasp = $giasp;
$this->hinhsp = $hinhsp;
$this->motasp = $motasp;
$this->idsanpham = $idsanpham;
}
}
When I run file "Getsp.php", result is white blank page.
I replace getsp.php with content:
include "connect.php";
// mysqli_set_charset($conn, "utf8");
$page = $_GET['page'];
$idsp = 1;
$space = 5;
$limit = ($page - 1) * $space;
$mangsanpham = array();
$query = "SELECT * FROM sanpham WHERE idsanpham = $idsp LIMIT $limit,$space";
$data = mysqli_query($conn,$query);
while ($row = mysqli_fetch_assoc($data)) {
array_push($mangsanpham, new Sanpham(
$row['id'],
$row['tensanpham'],
$row['giasanpham'],
$row['hinhanhsanpham'],
$row['motasanpham'],
$row['idsanpham']));
}
echo json_encode($mangsanpham);
class Sanpham{
function Sanpham($id, $tensp, $giasp, $hinhsp, $motasp, $idsanpham){
$this->id = $id;
$this->tensp = $tensp;
$this->giasp = $giasp;
$this->hinhsp = $hinhsp;
$this->motasp = $motasp;
$this->idsanpham = $idsanpham;
}
}
The result is not. Where did I wrong?
I tried 2 ways:
$json = json_encode($mangsanpham, JSON_PRETTY_PRINT);
print_r($json);
and
echo json_encode($mangsanpham);
The results are not encode JSON. Hope to get help from everyone!
To use array_push, you have to declare first variable as array
i.e $mangsanpham = array(); //before while loop
I am trying to create a JSON object as an array from the data received from the SQL Query. Currently the encoded JSON I have got is:
[{"firstname":"Student","lastname":"1"},{"firstname":"Student","lastname":"2"},{"firstname":"Student","lastname":"3"}]
The values I want to insert from another array, the values are in corresponding order to the each array in the JSON above: (JSON)
["85.00000","50.00000","90.00000"]
So the JSON should look like:
{"firstname":"Student","lastname":"1","grade":"85.00000"}
My Current Code:
//Provisional Array Setup for Grades
$grade = array();
$userid = array();
$sqldata = array();
foreach($json_d->assignments[0]->grades as $gradeInfo) {
$grade[] = $gradeInfo->grade;
$userid[] = $gradeInfo->userid;
}
//Server Details
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "moodle";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
foreach($userid as $id) {
$sql = "SELECT firstname, lastname FROM mdl_user WHERE id='$id'";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_array($result, MYSQL_ASSOC)) {
$sqldata[] = $row;
}
} else {
echo "ERROR!";
}
}
$sqlr = json_encode($sqldata);
$grd = json_encode($grade);
echo $sqlr;
echo $grd;
mysqli_close($conn);
try this code:
foreach($userid as $x => $id) {
$sql = "SELECT firstname, lastname FROM mdl_user WHERE id='$id'";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_array($result, MYSQL_ASSOC)) {
$row['grade'] = $grade[$x];
$sqldata[] = $row;
}
} else {
echo "ERROR!";
}
}
I added the Variable $x and added $row['grade'] with the same index on the $gradearray
function set_column_values($arr, $column_name, $column_values) {
$ret_arr = array_map(function($arr_value, $col_value) use ($column_name) {
$arr_value[$column_name] = $col_value;
return $arr_value;
}, $arr, $column_values);
return $ret_arr;
}
$sqldata = set_column_values($sqldata, 'grades', $grade);
$sqlr = json_encode($sqldata);
var_dump($sqlr);
Hope it helps!
I am fairly new to PHP slim but it's working great for me actually. But I have a problem that I think is really strange! I have a PHP file with all my API functions to get or edit data in my database. Each of these functions works great seperatly but when I uncomment them all and they are all active I get a 404 error when I want to use them or when I surf directly to them in my browser.
Here you can see all the functions I want to use:
//PHPSLIM
require '.././libs/Slim/Slim.php';
\Slim\Slim::registerAutoloader();
$categories = new \Slim\Slim();
$categories = \Slim\Slim::getInstance();
$categories->get('/categories', function(){
global $conn, $servername, $username, $password, $dbname;
mysql_connect($servername, $username, $password);
mysql_select_db($dbname);
$result = mysql_query("SELECT `categoryID`, `categoryName` FROM `category`");
while($line = mysql_fetch_array($result, MYSQL_NUM)) {
$cat[] = $line;
}
echoResponseCat(200, $cat);
});
function echoResponseCat($status_code, $response) {
global $categories;
$categories->status($status_code);
header('Content-Type: application/json');
$categories->contentType('application/json');
echo json_encode($response,JSON_NUMERIC_CHECK);
}
$categories->run();
//ALTER ORDER STATUS
$status = new \Slim\Slim();
$status = \Slim\Slim::getInstance();
$status->get('/orderPrepared/:orderID', function ($orderID) {
global $conn, $servername, $username, $password, $dbname;
if(isset($orderID)){
$sql = "UPDATE `order` SET `orderStatus`= 'done' WHERE `orderID` = '$orderID'";
mysql_connect($servername, $username, $password);
mysql_select_db($dbname);
$result = $conn->query($sql);
}
});
$status->run();
$app = new \Slim\Slim();
$app = \Slim\Slim::getInstance();
//GET ALL ORDERS
$app->get('/orders', function(){
$extranames = "";
$extrasprice = 0;
global $conn, $servername, $username, $password, $dbname;
$sql = "SELECT `orderID`, `customerID`, `storeID`, `orderDate`, `orderDeliveryDate`, `orderStatus` FROM `order`";
mysql_connect($servername, $username, $password);
mysql_select_db($dbname);
$query = mysql_query("SELECT `orderID`, `customerID`, `orderDate`, `orderDeliveryDate`, `orderStatus` FROM `order`");
$ordersall = array();
while($line = mysql_fetch_array($query, MYSQL_ASSOC)){
$orders[] = $line;
}
$count = 0;
$extrasprice = 0;
$ordersall = array();
$orderKeys = array('orderID', 'customerID', 'customerName', 'orderDate', 'orderDeliveryDate', 'orderStatus');
$orderKeys = array_combine($orderKeys, $orderKeys);
foreach($orders as $key => $looporders){
$extracounter = 1;
$sql = "SELECT `orderdetailID`, `productID`, `orderdetailAantal` FROM `orderdetail` WHERE `orderID` = '$looporders[orderID]'";
$result = $conn->query($sql);
//echo("orderID " . $looporders["orderID"] . " " . $result->num_rows ."/");
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$sql2 = "SELECT `productTitle`, `productPrijs` FROM `products` WHERE `productID` = '$row[productID]'";
$result2 = $conn->query($sql2);
if($result2->num_rows > 0) {
while($row2 = $result2->fetch_assoc()){
$productTitle = $row2["productTitle"];
$productPrijs = $row2["productPrijs"];
}
}
$sql3 = "SELECT `customerName` FROM `customers` WHERE `customerID` = '$looporders[customerID]'";
$result3 = $conn->query($sql3);
if($result3->num_rows > 0) {
while($row3 = $result3->fetch_assoc()){
$customerName = $row3["customerName"];
}
}
$sql4 = "SELECT `extraID` FROM `orderdetailextra` WHERE `orderdetailID` = '$row[orderdetailID]'";
$result4 = $conn->query($sql4);
if ($result4->num_rows > 0) {
while($row4 = $result4->fetch_assoc()) {
$sql5 = "SELECT `extraName`, `extraPrice` FROM `extra` WHERE `extraID` = '$row4[extraID]'";
$result5 = $conn->query($sql5);
if ($result5->num_rows > 0) {
while($row5 = $result5->fetch_assoc()) {
$extranames = $extranames . $row5["extraName"]. ', ';
$extrasprice += $row5["extraPrice"];
}
}
}
}
$orderID = $looporders["orderID"];
if(!isset($ordersall[$orderID])){
$ordersall[$orderID] = array_intersect_key($looporders,$orderKeys);
$ordersall[$orderID]["customerName"] = $customerName;
$ordersall[$orderID]['details'] = array();
$newdata = array(
"orderdetailID" => $row["orderdetailID"],
"productTitle" => $productTitle,
"productPrijs" => $productPrijs,
"aantal" => $row["orderdetailAantal"],
"extras" => substr($extranames, 0, -2),
"extrasPrice" => $extrasprice
);
array_push($ordersall[$orderID]['details'], $newdata);
}
else if(isset($ordersall[$orderID])){
$newdata = array(
"orderdetailID" => $row["orderdetailID"],
"productTitle" => $productTitle,
"productPrijs" => $productPrijs,
"aantal" => $row["orderdetailAantal"],
"extras" => substr($extranames, 0, -2),
"extrasPrice" => $extrasprice
);
array_push($ordersall[$orderID]['details'], $newdata);
}
$count++;
$extranames ="";
$extrasprice = 0;
}
}
}
echoResponse(200, $ordersall);
});
$app->run();
//GET ALL ORDERS FOR 1 CUSTOMER
$app->get('/orderoverview/:customerID', function ($customerID) {
global $conn, $servername, $username, $password, $dbname;
//1.1 GET ORDER (ID) AND NAME OF CUSTOMER
$sql = "SELECT `customerName` FROM `customers` WHERE `customerID` = $customerID";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$customername = $row["customerName"];
}
}
else {
echo "Customer name failure";
}
$sql = "SELECT `orderID` FROM `order` WHERE `customerID` = $customerID";
$result = $conn->query($sql);
if($result->num_rows > 1){
echo "You already have a pending order! <br>";
}
else if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$orderID = $row["orderID"];
}
step2($orderID, $customername);
} else {
echo "GET orderID failure";
}
});
$app->run();
Can someone tell me what I'm doing wrong?
You are calling run after each controller. But you only need to do this once. For your whole application
$app = new \Slim\Slim();
$app->get('/orderPrepared/:orderID', function ($orderID) {
});
.. assign all your controllers ..
$app->run();
I'm new to this, and was hoping someone may be able to help me, I have a mysql database with 4 fields "id, date, name, comment"
I have the following php file:
<html>
<head>
<title>Paging Using PHP</title>
</head>
<body>
<?php
$dbhost = 'localhost';
$dbuser = 'USERNAME';
$dbpass = 'PASSWORD';
$rec_limit = 5;
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db('DATABASE_NAME');
/* Get total number of records */
$sql = "SELECT count(id) FROM comments ";
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not get data: ' . mysql_error());
}
$row = mysql_fetch_array($retval, MYSQL_NUM );
$rec_count = $row[0];
if( isset($_GET{'page'} ) )
{
$page = $_GET{'page'} + 1;
$offset = $rec_limit * $page ;
}
else
{
$page = 0;
$offset = 0;
}
$left_rec = $rec_count - ($page * $rec_limit);
$sql = "SELECT * FROM comments ORDER BY id DESC";
"FROM comments ".
"LIMIT $offset, $rec_limit";
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not get data: ' . mysql_error());
}
while($row = mysql_fetch_array($retval, MYSQL_ASSOC))
{
echo "<strong>Date :{$row['date']} </strong><br> ".
"<strong>Name : {$row['name']} </strong><br> ".
"Comment : {$row['comment']} <br> ".
"<br><br>";
}
if( $page > 0 )
{
$last = $page - 2;
echo "Previous Page |";
echo "Next Page";
}
else if( $page == 0 )
{
echo "Next Page";
}
else if( $left_rec < $rec_limit )
{
$last = $page - 2;
echo "Previous Page";
}
mysql_close($conn);
?>
This all works fine, apart from I want it do display 5 results per page, can someone please tell me what I need to change, how and where?
Many thanks
This is working code. Just copy and paste. Do your echo. It will look nice if you echo it in table.
<?php
//DB CONNECTION HERE
$currentPage = $_SERVER["PHP_SELF"];
$rec_limit = 5;//This will display 5 result per page
$pageNum_view = 0;
if (isset($_GET['pageNum_view'])) {
$pageNum_view = $_GET['pageNum_view'];
}
$startRow_view = $pageNum_view * $rec_limit;
mysql_select_db($dbhost, $dbuser, dbpass);
$query_view = "SELECT * FROM comments ORDER BY id DESC";
$query_limit_view = sprintf("%s LIMIT %d, %d", $query_view, $startRow_view, $rec_limit);
$view = mysql_query($query_limit_view, $dbconnect) or die(mysql_error());
$row_view = mysql_fetch_assoc($view);
if (isset($_GET['totalRows_view'])) {
$totalRows_view = $_GET['totalRows_view'];
} else {
$all_view = mysql_query($query_view);
$totalRows_view = mysql_num_rows($all_view);
}
$totalPages_view = ceil($totalRows_view/$rec_limit)-1;
$queryString_view = "";
if (!empty($_SERVER['QUERY_STRING'])) {
$params = explode("&", $_SERVER['QUERY_STRING']);
$newParams = array();
foreach ($params as $param) {
if (stristr($param, "pageNum_view") == false &&
stristr($param, "totalRows_view") == false) {
array_push($newParams, $param);
}
}
if (count($newParams) != 0) {
$queryString_view = "&" . htmlentities(implode("&", $newParams));
}
}
$queryString_view = sprintf("&totalRows_view=%d%s", $totalRows_view,
$queryString_view);
?>
//Here echo
<?php if ($pageNum_view > 0) { // Show if not first page ?>
<a href="<?php printf("%s?pageNum_view=%d%s", $currentPage, 0,
$queryString_view); ?>">FIRST</a>
<?php } // Show if not first page ?>
<?php if ($pageNum_view > 0) { // Show if not first page ?>
PREVIOUS
<?php } // Show if not first page ?>
<?php if ($pageNum_view < $totalPages_view) { // Show if not last page ?>
NEXT
<?php } // Show if not last page ?>
<?php if ($pageNum_view < $totalPages_view) { // Show if not last page ?>
LAST
<?php } // Show if not last page ?>
<?php
mysql_free_result($view);
?>