I am new here and this is my first post
I need help for a college project.
We are programming a raspberry pie so that is measures temperature and air humidity and visualize the data on an html page.
But we have a problem to make the visualize right.
We take the data from myadminphp and show it graphically, but the time stamp is not steady it change the time to time at the moment minus 3 hours but we want to have it fixed every 3 hours.
Php code:
$lastDatetime = $db->query("select date_time
from measurements
where id=(
select max(id)
from measurements
)")
->fetch(PDO::FETCH_ASSOC)["date_time"];
$thisDay = $lastDatetime;
$dataLastSevenDays = array();
for ($i = 0; $i < 56; $i++) {
$maxTemperatureThisDay = $db->query("select value
from measurements
where date_time like '" . substr($thisDay, 0, 13) . "%'
and channel = 1
limit 1"
)
->fetch(PDO::FETCH_ASSOC)["value"];
//channel 1 Temp
$maxBrightnessThisDayThisDay =
$db->query("select value
from measurements
where date_time like '" . substr($thisDay, 0, 13) . "%'
and channel = 2
limit 1")
->fetch(PDO::FETCH_ASSOC)["value"]; //channel 2 Licht
$maxHumidityThisDay =
$db->query("select value
from measurements
where date_time like '" . substr($thisDay, 0, 13) . "%'
and channel = 4
limit 1")
->fetch(PDO::FETCH_ASSOC)["value"]; //channel 4 Luftfeuchtigkeit
$thisDay = date_sub(new DateTime($thisDay), new DateInterval('PT10800S'))->format('Y-m-d H:i:s');
$dataLastSevenDays[$i] = array($thisDay, $maxTemperatureThisDay, $maxBrightnessThisDayThisDay, $maxHumidityThisDay);
}
the html code:
<script>
var ctx = document.getElementById('temperature').getContext('2d');
var chart = new Chart(ctx, {
type: 'line',
data: {
labels: [
<?php
for ($i = 56; $i > 0; $i--) {
echo '"' . $dataLastSevenDays[$i][0] . '",';
}
?>
],
datasets: [{
label: "gemessene Temperatur",
borderColor: 'rgb(16, 119, 237)',
data: [
<?php
for ($i = 56; $i > 0; $i--) {
echo '"' . $dataLastSevenDays[$i][1] . '",';
}
?>
]}]
},
options: {}
});
</script>
Related
I'm trying to make a little PHP script for fun, and I'm a little stuck.
I want to divide an integer (for example 5) over multiple values.
For example:
$total = 5;
$mike = 0;
$ralf = 0;
$ashley = 0;
// Run the magic here
echo "Mike has " . $mike . " apples, Ralf has " . $ralf ." apples and Ashley has " . $ashley . " apples";
The output that I expect would look something like this:
Mike has 2 apples, Ralf has 1 apples and Ashley has 2 apples
Is there a way how to do this? :)
I can't do this hard coded, because I want the values to be randomized.
Cheers
Do it like this:
$total = 5;
$mike = rand(1,$total-2); // so that max value is 3 (everyone should get at least 1) ($total - $numberOfVarsToDistributeTheValueTo + 1)
$ralf = rand(1,$total - $mike - 1); // if 3 goes to mike, only 1 goes to ralf
$ashley = $total - $mike - $ralf; // i hope you understand.
// use it.
Something like this would work:
$people = array('mike','ralf','ashley');
$num = count($people);
$sum = 5; // TOTAL SUM TO DIVIDE
$groups = array();
$group = 0;
while(array_sum($groups) != $sum) {
$groups[$group] = mt_rand(0, $sum/mt_rand(1,5));
if(++$group == $num){
$group = 0;
}
}
// COMBINE ARRAY KEYS WITH VALUES
$total = array_combine($people, $groups);
echo "Mike has " . $total['mike'] . " apples, Ralf has " . $total['ralf'] ." apples and Ashley has " . $total['ashley'] . " apples";
Solution is inspired from this answer: https://stackoverflow.com/a/7289357/1363190
Hope This function will do your work . it can work for variable # of persons also.
divide_items(10,['mike','ralf','ashley']);
function divide_items($total=1,array $persons){
$progressed = 0;
for($i=0;$i<count($persons);$i++){
echo $random_count = rand(1,$total);
if(($i==(count($persons)-1)) && $progressed<$total ){
$random_count1 =$total - $progressed;
echo $persons[$i]." has ".$random_count1 ." Items<br>";
continue;
}
$progressed = $progressed+$random_count;
if($progressed<=$total){
echo $persons[$i]." has ".$random_count ." Items<br>";
}else{
echo $persons[$i]." has 0 Item<br>";
}
$total = $total-$random_count;
$progressed = 0;
}
}
So I currently have graphs with have static data from JQ, I'm attempting to get the data from a DB using PHP. I've began the logic but struggling to move forward, Any ideas would be appreciated.. So far the graph outputs blank, only works when I use static data.
Used 0 in the output array as a test
PHP<?php
$userID = $_SESSION["userid"];
$days = array();
$query = "SELECT timeSpent
FROM gymTime
WHERE userid = '$userID'";
$result = mysqli_query($conn, $query);
$i=0;
while($row = $result->fetch_assoc()) {
$days[$i] = $row["timeSpent"];
$i++;
}
?
JQ <script>
// in php you simply need to create the two arrays and teh functionality will work
// monthly set to minutes
var myTimeMon = ;
var myMonths = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];
// weekly data in mins
var myTimeWeek = [<?php echo $days[0]; ?>];
var myDays= ["Mon","Tue","Wed","Thur","Fri","Sat","Sun"];
// default values to be displayed when the page loads
var myLabels = myDays;
var mydata = myTimeWeek;
// store value of radiobutton
var currentValue = "m"
var displayData=[];
function contoMins(){
// change the values of the array
for(i=0; i<mydata.length; i++){
mydata[i]=mydata[i]*60;
}
destroyChart();
}
// destroy the chart so that it does not load on top of itself
function destroyChart(){
window.myBar.destroy();
buildChart();
}
function buildChart(){
displayData = mydata;
var barChartData = {
labels : myLabels,
//barValueSpacing : 25,
//barStrokeWidth : 40,
datasets : [
{
fillColor : "rgba(220,220,220,0.5)",
strokeColor : "rgba(220,220,220,0.8)",
highlightFill: "rgba(220,220,220,0.75)",
highlightStroke: "rgba(220,220,220,1)",
data: displayData
}
]
}
var ctx = document.getElementById("canvas").getContext("2d");
window.myBar = new Chart(ctx).Bar(barChartData, {
barValueSpacing : 10,
});
}
buildChart();
//sendData();
</script>
DB Structure
http://prntscr.com/avdg9r
Webpage
http://prntscr.com/avdgeq
This always sets $i equal to 0.
while($row = $result->fetch_assoc()) {
$i=0;
$days[$i] = $row["timeSpent"];
$i++;
}
Move $i = 0 outside the while loop.
$i=0;
while($row = $result->fetch_assoc()) {
$days[$i] = $row["timeSpent"];
$i++;
}
Also, loop through your $days array.
var myTimeWeek = [<?php echo $days[0]; ?>];
will only display the first element in $days. You need to loop through the array.
var myTimeWeek = [
<?php
$i = 0;
$total = 0;
foreach ($days as $day)
{
if ($i > 0) echo ', ';
echo '"' . $day . '"';
$total = $total + $day;
$i++;
}
?>
]
Move your $i outside the loop-block, otherwise the $i will be 0 for each iteration
$i=0;
while($row = $result->fetch_assoc()) {
$days[$i] = $row["timeSpent"];
$i++;
}
I've wrote a script in PHP for an university big data project.
The following code should support following function:
Read amount of data from a table
read a subset of the same table und extend it with 2 columns which calculate 2 values.
generate f.e. 1000 inserts and commit them to an other table
do this for the whole dataset of point 1
My problem:
0-1000:
my solution inserts in the first try 1000 datalines
1000-2000:
in this step it inserts 2000 datalines, so after the 2nd step it seems to insert 0-2000 datalines of the origin dataset. In sum 3000 datalines.
I'm a little bit out of ideas... I don't see my failure.
<?php
$user = 'root';
$pass = '';
$kill = 0;
echo 'Connecting to DB:';
try {
$db1 = new PDO('mysql:host=localhost;dbname=itt2_joined;charset=utf8',$user,$pass);
$db1->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
echo "OK \nGOING2COPY!\n";
}
catch(PDOException $ex) {
echo " Failed - Process stopped!\n";
$kill = 1;
}
if(!$kill) {
$stmt = 'SELECT
`id_transaction`
FROM
`database_joined_full`
WHERE
`relative_delivery_date` > 0
AND
`relative_received_date` > 0
AND
`relative_issued_date` > 0';
$setSize = $db1->query($stmt)->rowCount();
echo "No. Of Datasets: " . $setSize . "\n";
$stepSize = 1000;
echo "Start Copy $stepSize Datasets per Query! \n";
$copy = 1;
$lower = 0;
$upper = 0;
echo "[";
while($copy) {
$lower = $upper;
$upper += $stepSize;
$upper = ($upper > $setSize ? $setSize : $upper);
$data = $db1->query("SELECT
`id_transaction`,
`id_order_line`,
`relative_transaction_date`,
`relative_requested_date`,
`new_requested_qty`, `new_requested_price`,
`relative_suggested_date`,
`new_suggested_qty`,
`delivery_qty`,
`relative_delivery_date`,
`received_qty`,
`relative_received_date`,
`id_order_header`,
`delivery_counter`,
`relative_issued_date`,
`relative_xcurrent_date`,
`issued_quantity`,
`current_quantity`,
`product_code`,
`destination`,
`relative_issuing_date`,
`delivery_location`,
`issuer`,
`id_supplier`,
`currency`,
`shipment`,
`issued_price4unit`,
`current_price4unit`,
`total_delivered`
FROM
`database_joined_full`
WHERE
`relative_delivery_date` > 0
AND
`relative_received_date` > 0
AND
`relative_issued_date` > 0
LIMIT $lower OFFSET $stepSize")->fetchAll();
$db1->beginTransaction();
foreach($data as $row) {
$sql = "";
$sql = "INSERT INTO `refactored_data` (`id_transaction`, `id_order_line`, `relative_transaction_date`,
`relative_requested_date`, `new_requested_qty`, `new_requested_price`, `relative_suggested_date`,
`new_suggested_qty`, `delivery_qty`, `relative_delivery_date`, `received_qty`,
`relative_received_date`, `id_order_header`, `delivery_counter`, `relative_issued_date`,
`relative_xcurrent_date`, `issued_quantity`, `current_quantity`, `product_code`, `destination`,
`relative_issuing_date`, `delivery_location`, `issuer`, `id_supplier`, `currency`, `shipment`,
`issued_price4unit`, `current_price4unit`, `total_delivered`, `shipment_delay`, `sending_delayed`) VALUES ";
$sql .= "(";
for($i = 0; $i<sizeof($row)/2; $i++) {
$sql .= "'".$row[$i] . "', ";
}
$sql .= $row['relative_received_date'] - $row['relative_delivery_date'] . ',';
$sql .= ($row['relative_received_date'] <= $row['relative_issued_date'] ? 1 : 0) .')';
$db1->prepare($sql)->execute();
}
$db1->commit();
// Statusbar
//echo "\n$lower - $upper\n";
$perc = ceil(($upper/$setSize) *40);
$bar = "\r[". str_repeat("=", $perc - 1). ">";
$bar .= str_repeat(" ", 40 - $perc) . "] - " . number_format($upper / $setSize * 100, 3) ."% ";
echo "\033$bar"; // Note the \033. Put the cursor at the beginning of the line
//While_Exit
$copy = ($upper == $setSize ? 0 : 1);
//$copy = 0;
}
echo "\nall done, BYE! \n";
}
?>
You're using the stepsize as the offset each time:
LIMIT $lower OFFSET $stepSize
Should be:
LIMIT $stepSize OFFSET $lower
Oh thank you! I haven't seen the failure.
Now the code works, nearly completely, my last problem is the following:
in the first Select query i get from '->rowCount();' the number of rows of the select query.
But with my insertion copys a bit more data. But in the second Select i have the same Where clause likewise the first Select query.
I get from the CLI-Print : No. of Rows: 655056
and it writes in the Database 658597
so how do i get the 3541 rows?
or is maybe a failure inside the Insert?
Greetings
The project is a web calendar/scheduler using php. The idea is that a user can schedule a job that is assigned to specific machine at a specific time and others can see the job schedule and which 'asset' the job is assigned to. The scheduling works, however, I cannot tie the data to header/columns they belong to. It looks like this:
<?php
include_once("HTML/TABLE.PHP");
$data = array( 0=>array(1,'asset1','2013-07-24 10:00:00', '2013-07-24 12:00:00','red',2),
1=>array(2,'asset1','2013-07-24 12:00:00', '2013-07-24 13:00:00','green',3),
2=>array(3,'asset2','2013-07-24 11:00:00', '2013-07-24 12:00:00','blue', 4),
3=>array(4,'asset2','2013-07-24 12:00:00', '2013-07-24 14:00:00','red', 2),
4=>array(5,'asset3','2013-07-24 11:30:00', '2013-07-24 12:00:00','green', 4),
5=>array(6,'asset4','2013-07-24 12:00:00', '2013-07-24 14:00:00','blue', 3),
6=>array(7,'asset1','2013-07-24 11:45:00', '2013-07-24 13:00:00','red', 1),
7=>array(8,'asset4','2013-07-24 13:00:00', '2013-07-24 15:00:00','yellow', 5)
);
$attrs = array( 'class' => 'main',
'id' => 'main_id',
'width' => '100%',
'border' => '1',
'cellspacing' => '0',
'cellpadding' => '0');
$table = new HTML_Table($attrs);
$table->setAutoGrow(true);
$table->setAutoFill('n/a');
$heads = array( array('asset1','asset2','asset3','asset4'));
$i = 1;
foreach($heads as $val)
{
$table->setHeaderContents(0, $i++, $val);
unset($val);
}
$now = date('U');
$offset = ($now % 900);
$now = $now-$offset;
for ($i = 0;$i < 33; $i++)
{
$table->setHeaderContents($i,0, date('g:i',$now));
$now += 900;
}
$cellPosition = 1;
$rowCounter = 1;
for ($i=0;$i < count($data);$i++)
{
$table->setCellAttributes ($rowCounter,$cellPosition,' bgcolor = '. $data[$i][4]. ' rowspan=' . $data[$i][5]);
$table->setCellContents($rowCounter,$cellPosition,"Job# ".$data[$i][0] . " belongs to: " . $data[$i][1]);
$cellPosition++;
$rowCounter =1;
}
echo $table->display();
?>
How can I tie the information to only the column it belongs to?
I have gotten this far, but I get odd results if the first column is true:
$cellPosition = 0;
$rowCounter = 1;
for ($x=0;$x <= count($heads);$x++)
{
for ($i=0;$i < count($data);$i++)
{
if ($data[$i][1] == $table->getCellContents(0,$x))
{
$table->setCellAttributes ($rowCounter,$cellPosition,' bgcolor = '. $data[$i][4]. ' rowspan=' . $data[$i][5]);
$table->setCellContents($rowCounter,$cellPosition,"Job# ".$data[$i][0] . " belongs to: " . $data[$i][1]);
//$cellPosition++;
//echo ;
echo "<br> The current count of x = : ". $x;
echo "<br>" . $table->getCellContents(0,$x) . " Matches " . $table->getCellContents(0,$x) . " at index " . $i;
$rowCounter += $data[$i][5];
}
else
{
$rowCounter = 1;
}
}
$cellPosition++;
Ok this is working, but only if the array results are in order by asset. If not the row is reset to row 1 and the second entry overlays the previous.
$cellPosition = 0;
$rowCounter = 1;
for ($x=0;$x <= count($heads);$x++)
{
for ($i=0;$i < count($data);$i++)
{
if ($data[$i][1] == $table->getCellContents(0,$x))
{
$table->setCellAttributes ($rowCounter,$cellPosition,' bgcolor = '. $data[$i][4]. ' rowspan=' . $data[$i][5]);
$table->setCellContents($rowCounter,$cellPosition,"Job# ".$data[$i][0] . " belongs to: " . $data[$i][1]);
echo "<br> The current count of x = : ". $x;
echo "<br>" . $table->getCellContents(0,$x) . " Matches " . $data[$i][1] . " at index " . $i;
$rowCounter += $data[$i][5];
}
else
{
$rowCounter = 1;
}
}
$cellPosition++;
}
My solution is to presort the records using sql order by. I don't know how elegant that is but for the moment it is working and I can move further into this project. Any suggestions would be welcome. Thanks!
I am trying to get my graph to display dates on the x axis instead of the timestamps. I've searched and read other posts and still can't get it to budge. Here's my code:
for($i = 0; $i < 3; $i++)
{
$j = $i + 1;
$query = "SELECT UNIX_TIMESTAMP(date_added)*1000, COUNT(id)
FROM likes
WHERE date_added BETWEEN
DATE_SUB(CURDATE(), INTERVAL $j MONTH)
AND DATE_SUB(CURDATE(), INTERVAL $i MONTH)";
$result = mysql_query($query);
echo mysql_error();
$date = mysql_result($result, 0, 0);
$count = mysql_result($result, 0, 1);
$pair = array( (string)$date, (int)$count );
array_push($data_series1, $pair);
}
$.ajax({
url: 'graph_likes.php?get_data=month',
dataType: 'json',
success: function(returned) {
$.plot($('#container'),
[{
data: returned,
points:
{
show: true
},
lines:
{
show: true
},
color: '#00d6e2',
xaxis:
{
mode: 'time'
}
}]);
}
});
If you want flot to display your timestamps nicely formatted, you can try using the timestamp format option (called timeformat):
...
xaxis:
{
mode: 'time',
timeformat: "%y/%m/%d"
}
...
You find the option explained in this document: http://people.iola.dk/olau/flot/API.txt , look for the section called Time series data.