PHP, Add gmdate to gmdate - php

I have a code that looks like this:
$dagtidhelg = gmdate('H:i', $diffMorning) . "\n";
$kvallstidhelg = gmdate('H:i', $diffNight);
This code runs several times per page since its runt every time a row is loaded from mysql.
It can return a time value ie 08:15 and 09:30. This is the lenght of two work sessions.
That works great but now Im stuck, I want to display the total of every work session at the bottom. I have tried this:
$dagtidhelgtotal = $dagtidhelgtotal + $dagtidhelg;
$kvalltidhelgtotal = $kvalltidhelgtotal + $kvallstidhelg;
But that only adds the hours togheter, it wont even display the :
So Im guessing that Im doing this totaly wrong.
How can I add these times togheter? Maybe convert them to minutes, then add them all togheter?

Add duration together is simple .But you must keep in mind that duration and date are two things completely different. You can write 100:08 for duration but not for date. If your purpose is to keep a duration counter on(one or) every page(s) you need to build a system based on $_SESSION variable.
To add two duree you can proceed like this:
function addDuration($duration1,$duration2){
$result=array_map(function($x,$y){return sprintf("%'.02d", $x+$y);},explode(':',$duration1),explode(':',$duration2));
if($result[1]>60){
$result[0]=sprintf("%'.02d",$result[0]+(int)$result[1]/60);
$result[1]=sprintf("%'.02d",$result[1]%60);
}elseif($result[1]==60){
$result[1]="00";
$result[0]=sprintf("%'.02d",$result[0]+1);
}
return join(':',$result);
}
and the usage in your case could be:
$dagtidhelgtotal = addDuration($dagtidhelgtotal,$dagtidhelg);
if we suppose that
$dagtidhelgtotal ==='100:09' && $dagtidhelg === '08:08'
then after the addition
$dagtidhelgtotal will be equal to '108:17';

Related

Adding two times from database

im a newbie in PHP and im trying to solve this situation as much as i can but still don't get/know the right answer.
I have a table with 2 columns in database with time datatype
Lunch Break
00:01:00 00:00:30
Im trying to fetch the data and add the two times, but i always get the wrong value.
I have this code:
$time[$x] =$row['break'] + $row['lunch'];
$totalAux[$x] = $time[$x];
Output is : "00:00:00"
The i try this one:
$time[$x] =strtotime($row['break']) + strtotime($row['lunch']);
$totalAux[$x] = $time[$x];
And get an ouput of "00:00:00"
Then lastly tried this one:
$time[$x] =strtotime($row['break']) + strtotime($row['lunch']);
$totalAux[$x] = date('H:i:s', $time[$x]);
Output was: "09:33:14"
Please Help Guys .
You can use ADDTIME function from MySQL:
SELECT Lunch, Break, ADDTIME(Lunch, Break) FROM table_name;
sqlfiddle
Why don't you use the TIMEDIFF() and ADDTIME() functions which is to get the difference or to add times respectively in mysql so that it would be resolved there and php will just have to pick it up.
You need to use also TIME_FORMAT() in order to get the hours, minutes and seconds:
SELECT TIME_FORMAT(ADDTIME(lunch, breaks),'%H:%i:%s') as TimeTotal
FROM lunchbreaks;
SELECT TIME_FORMAT(TIMEDIFF(lunch, breaks),'%H:%i:%s') as TimeDifference
FROM lunchbreaks;
See the Demo

Network Monitoring

Image : http://i40.tinypic.com/2hodx55.png
I have built a Network Interface Monitor using Php and SNMP , but now when i execute it on localhost i see my graph goes to origin(0) again and again (Please see the image) and also the speed on Y axis is wrong. At times it goes in Millons and Millions.
please can anyone tell me what is the problem in the code below
<?php
$int="wlan0";
session_start();
$rx0 =snmpget('localhost','public','.1.3.6.1.2.1.2.2.1.10.3');
$tx0 =snmpget('localhost','public','.1.3.6.1.2.1.2.2.1.16.3');
sleep(5);
$rx1 =snmpget('localhost','public','.1.3.6.1.2.1.2.2.1.10.3');
$tx1 =snmpget('localhost','public','.1.3.6.1.2.1.2.2.1.16.3');
$rx0 = substr($rx0, 11);
$tx0 = substr($tx0, 11);
$rx1 = substr($rx1, 11);
$tx1 = substr($tx1, 11);
$tBps = $tx1 - $tx0;
$rBps = $rx1 - $rx0;
$round_rx=$rBps;
$round_tx=$tBps;
$time=date("U")."000";
$_SESSION['rx'][] = "[$time, $round_rx]";
$_SESSION['tx'][] = "[$time, $round_tx]";
$data['label'] = $int;
$data['data'] = $_SESSION['rx'];
if (count($_SESSION['rx'])>60)
{
$x = min(array_keys($_SESSION['rx']));
unset($_SESSION['rx'][$x]);
}
echo '{"label":"'.$int.'","data":['.implode($_SESSION['rx'], ",").']}';
?>
What you are seeing here is a classic case of polling a counter faster than its refresh interval. It is often the case that counters (in this case, interface counters) are updated every few seconds (10-15 seconds is a common value).
If the counter updates every 15 seconds, and you ask for data every 5 seconds, then you will receive the same value once or twice in a row (depending on latency, processing time, etc.). If you receive the same value twice, then you will see a zero value for the delta (which is what your image shows).
There are two ways to get around this:
Ask for data less frequently than the counters are updated (30-second polling usually works fine). Obviously, if you can find out the exact refresh interval, then you can use that.
Modify the configuration of your equipment to refresh its counters faster. Sometimes this is possible, sometimes it is not; it just depends on the manufacturer, the software, and what has been implemented.
For Net-SNMP "snmpd" daemons, you can walk NET-SNMP-AGENT-MIB::nsCacheTable (1.3.6.1.4.1.8072.1.5.3) for more information about its internal caching of counters.
For example:
snmpwalk -v2c -cpublic localhost 1.3.6.1.4.1.8072.1.5.3 | grep .1.3.6.1.2.1.2.2
NET-SNMP-AGENT-MIB::nsCacheTimeout.1.3.6.1.2.1.2.2 = INTEGER: 3
NET-SNMP-AGENT-MIB::nsCacheStatus.1.3.6.1.2.1.2.2 = INTEGER: cached(4)
Here, you can see that my particular box is caching IF-MIB::ifTable (.1.3.6.1.2.1.2.2), which is the table that you're using, every three seconds. In my case, I would not ask for data any more often than every three seconds. NET-SNMP-AGENT-MIB::nsCacheTimeout (.1.3.6.1.4.1.8072.1.5.3.1.2) is marked as read-write, so you might be able to issue an a "set" command to change the caching duration.

Store a variable as variable in database

Hello im building a multilenguaje app in php, this is the first time i handle multilenguaje, im trying to do it like this.
For months for example
i have a table "months" with id | month estructure
in the users table i have id | username | month_id
my guess (bad guess) its that i can save for example $january direct on the database so in the php when its called, it looked for the defined variable.
$january = "january"; and if im on spanish web then i change this to $january = "Enero";
but this is not working (obviusly because it prints as a result of a call $january, Its saved as $january in the database)
How is the best method for what im trying to do.. cause im lost in this point.. and i need this estructure in the database for a lot of reasons i wont mention, right now,
thanks!
My code
This $row2['months']
Print this $january
Even when in the php code i have set $january = "enero";
You might rethink your strategy.
Example:
For 10 languages if you keep 10 php files defining the month names or actually all language locale words in, it will be sufficient and you can include them without disturbing the database.
<?php
// this is words_en.php, you can make another like words_de.php etc.
$months = array('january','february','march','april'....etc );
?>
If you structure your locale file consistently for instance:
$msgs = array(
'MSG1'=>'first message',...
}
keeping only the references(like'MSG1') in your code and also in your database will be sufficient. For the months, you can keep them apart from $msgs since their use is specific and numeric indexing adds more consistency to coding for their case.
Note that this is not the only method for language locales but this is an easy to maintain version.
You should save the users locale e.g. en_US in your table and base further translations on that value with a fallback to the default language.
To get php to evaluate that variable, what you need to do is eval:
$january='Enero';
$row='$january';
echo $row; //Prints $january
echo PHP_EOL;
echo eval("return ".$row.";"); //Prints Enero
Here that is in ideOne: http://ideone.com/f0LCT0

Program a Changing Daily Message

How would I go about programming a daily message on my site that changes daily? I'm thinking of preloading all the messages in a MySQL database.
Any help would be appreciated!
Thanks,
I've tried
$msg_sql = "SELECT * FROM ".TABLE_PREFIX."quotes ORDER BY rand(curdate()) LIMIT 3";
$msg_res = mysqli_fetch_assoc(mysqli_query($link, $msg_sql));
But this only grabs the first MySQL result?
If you want a real message changing daily, you actually don't need to rely on a database or anything fancy. A simple idea might be to create a directory (say /var/www/motds) and populate it with files named YYYY-MM-DD.txt (where YYYY is a 4 digit year number, MM is a two digit month number and DD is a 2 digit day number).
Then, the only thing you need to do in order to display your motd is:
$filename = '/var/www/motds/'.date("Y-m-d").'.txt';
if (file_exists($filename)) {
echo file_get_contents($filename);
}
If you want your daily messages to be taken from a pool of entries (that you can pre-load), you might do something as follows:
$files = scandir('/var/www/motds'); // put files into an array
$messagecount = count($files) - 2; // .. and . shall not be considered
$day = date("z"); // what day do we have today?
echo file_get_contents('/var/www/motds/' . $files[($day % $messagecount) + 2]);
There are plenty of ways to get this done. You list PHP in your tags, so maybe check here:
PHP Script: Quote of the Day
or maybe here

Why is my MySQL INSERT query inserting 3 identical rows?

I am trying to track what users are searching for on my site (from a simple search form on the front page) with PHP and MySQL.
At the end of all my queries I am using this query:
INSERT INTO `DiggerActivity_Searches` (
`SearchTerms`,
`SearchType`,
`NumResults`,
`Location`,
`Date`,
`Time`
) VALUES (
'SearchKeywords',
'SearchTypes',
'NumberOfResults',
'User'sLocation',
'CurDate',
'CurTime'
)
Now, whenever there is a new search keyword, it inserts 3 identical rows. However, if I refresh the page it only inserts 1 row, as it should.
The values are passed as a GET like this (I have mod rewritten the URL stuff):
http://www.mysite.com/Search-Category-Search_these_words
You might want to check first whether your script executes the query three times or the script is invoked three times (e.g. by some browser addons).
If you do not have a debugger installed you can use something like
function trace_log() {
static $magic = null;
if (is_null($magic)) {
$magic = uniqid();
}
$s = $magic . ' '. microtime(true) . ":\r\n";
foreach( debug_backtrace() as $d) {
$s .= ' '. $d['file'].'#'.$d['line']."\r\n";
}
file_put_contents('trace_log.txt', $s, FILE_APPEND);
}
...
trace_log();
mysql_query(....) // or stmt->execute() or whatever you use to execute the query.
If the first value of each log entry (the "magic" id) in trace_log.txt changes, your script is invoked multiple times. If it's the same for all three calls to trace_log(), your script executes the query three times.
Your table is missing a primary key. Id suggest a PK like search ID or something similar
Read more about this at Unique key - Wikipedia
Just know you are not alone in dealing with this strange bug.
This same problem showed up on my website in the past few days as well. The only thing I recently added was a third party banner ad.
SOLUTION: I commented out the banner ad script (Hint: from search engine that starts with a G) and everything was good again.
I was just going to make a comment put need more reputation to so...
Anyway, similar happened to me. Turns out I was echoing out debug information above the header causing the browser to reload automatically. Easiest way to check is just use
<script type="text/javascript">alert("loading");</alert>
in the header and see how many times you see it.

Categories