calculate time difference in minute mysql and php - mysql

I have a table tem_test in this table one field is start_time which has DATETIME datatype and I want to compare this date with the current datetime; and if time is greater than 30 minute select the data for fetch....
like
if( user passed 30 minute )
{
// then update other table with user's info where userid ='user who crossed the 30 minute';
}
else
{
// do sometihing ....
}
<?php
<?php
$intranet_connect = mysql_connect('localhost','root',''); //create connection to intranet host
$radius_connect = mysql_connect('localhost','root',''); //creates connection to radius
mysql_select_db('db_intranet',$intranet_connect); //using db_intranet database with $intranet_connect host connection
$query = mysql_query('SELECT username,srvid,start_time FROM temp_day_test WHERE status="yes"',$intranet_connect); //check if service is on test mode then perform...below
while($row = mysql_fetch_assoc($query)) //fetch selected data from table
{
$data[]=$row;
}
$data['srvid']= $srvid; //hold service id in $srvid
$data['username'] = $username;
$data['start_time']=$startTime;
$currentTime = date('Y-m-d H(idea)(worry)'); //create current date time with timezone Asia/kathmandu. NOTE: set time zone in PHP.INI, default.timezone=Asia/Kathmandu
$timeDifference = (strtotime($currentTime) - strtotime($startTime)); //Calculate time difrence between test start time and test end time
if($timeDifference >1800)// if time exceeds 30 minute then...
{
echo $data['username'];
echo $data['srvid'];exit;
mysql_select_db('radius',$radius_connect); //select radius database
$query = mysql_query('UPDATE rm_users SET srvid="'.$srvid.'" WHERE srvid= 44 ', $radius_connect);
if(!$query)
{
die(mysql_error());
}
}
?>

You can use the date_diff function in php. or the TimeDiff() in MySQL, you choose which way suits you best.

Related

How do I reset a MySQL column in a table every year?

I have a column named lv_casual in a table called tbl_employees. I need to reset the column to 0 at a specific date every year.
You can use MySQL event schedule. Providing an example below.
You have to enable the schedular first
SET GLOBAL event_scheduler = ON;
Then create the event
CREATE EVENT your_event_name
ON SCHEDULE EVERY 1 YEAR
STARTS '2021-10-12 00:00:00'
DO
UPDATE table SET column=0;
Check MySQL document for creating event
You can use a cron job to run once per year at end of the year, create a script that will reset all the records on that column to 0.
/usr/local/bin/ea-php99 /home2/accounname/https://example.com/cron_execute_file
okay bro this how your execute file should look like cron_execute_file.php
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection to db
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "UPDATE employees SET leaves='12' WHERE leaves >= 0";
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
$conn->close();
?>
N/B: [#Shaido][1] and any dauche bag thinking of, Please stop editing my answers, just give your own answers, adding fullstops and grammar to my answers to gain budges is a lame thing note this is not a English grammar class. Stay away from my answers, give your own answers. Polite Notice failure to I'll send some visitors to you machines.
[1]: https://stackoverflow.com/users/7579547/shaido

Set maximum row of the table with page-break and show remaining data to next page

I want to set the maximum number of row in each table and continue the data to the next page in the html. For example, I have 44 records and I need to show only 10 records in first html page and another 10 in another html page and goes on and finally with the last 4 records in the last page. I just need to know the logic to be used in this with for loop.
I tried this to display the first 10 records but, how to display the other records
<% for (var i = 0; i < 10; i++) { %>
I guess you need a simple pager but with data on different independent pages
Here is a part of code ... you just need to change $pageno variable to current page .. or you can catch it with GET or extract from pagename.
if (isset($_GET['pageno'])) {
$pageno = $_GET['pageno'];
} else {
$pageno = 1;
}
$no_of_records_per_page = 10;
$offset = ($pageno-1) * $no_of_records_per_page;
$conn=mysqli_connect("localhost","my_user","my_password","my_db");
// Check connection
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
die();
}
$total_pages_sql = "SELECT COUNT(*) FROM table";
$result = mysqli_query($conn,$total_pages_sql);
$total_rows = mysqli_fetch_array($result)[0];
$total_pages = ceil($total_rows / $no_of_records_per_page);
$sql = "SELECT * FROM table LIMIT $offset, $no_of_records_per_page";
$res_data = mysqli_query($conn,$sql);
while($row = mysqli_fetch_array($res_data)){
//here goes the data
}
mysqli_close($conn);

When will the database connection be closed in prestashop 1.6.1.3 version?

When will the database connection be closed in prestashop 1.6.1.3 after a db instance is created by $db = Db::getInstance();
Do I need to close the database connection manually by writing any code db close function?
Or the db class in prestashop will handle this?
Actually when will be the PrestaShop db connection will be closed after a db object is created by $db = Db::getInstance();?
See below code which is a simple php file in my root directory of prestashop to update one of my tables and this page is called every one minute by cron job task ,here I am not closing the connection anywhere ,do we need to close it ?
$CheckStatusSql = "select * from ticket_status where item_id='$ItemID' and ticket_series='$TicketSeries' and status='BOOKED' ";
$db = Db::getInstance();
$result = $db->executeS($CheckStatusSql, false);
$ChangeStatus ='';
while ($row = $db->nextRow($result)) {
$status = $row['status'];
$booked_on = $row['booked_on'];
$ticket_no = $row['ticket_no'];
$to_time = strtotime(date("Y-m-d H:i:s"));// Time Now
$from_time = strtotime($booked_on); //Booked Time
$time_diff_minutes=round(abs($to_time - $from_time) / 60,2);
if($time_diff_minutes>$checkMinutes){
$ChangeStatus=$ChangeStatus."Booked ticket no: '".$ticket_no."' exceeds 30 Minutes and its now about ".$time_diff_minutes." minutes, status changed to AVAILABLE<br><br\>";
$updateSql = "UPDATE ticket_status SET status = 'AVAILABLE', booked_on = NULL WHERE item_id='$ItemID' and ticket_series='$TicketSeries' and status='BOOKED' and ticket_no='$ticket_no'";
$bookResult = $db->executeS($updateSql, false);
}
}
That is I am just including the config file (require 'config/config.inc.php';) and creating a db object and then executing my query as shown below :
require 'config/config.inc.php';
$checkMinutes = 30;// In minutes
$checkTimeInSeconds = $checkMinutes*60;
$sql = 'SELECT * FROM ps_ticket WHERE status=5';
$db = Db::getInstance();
$result = $db->executeS($sql, false);
$i=1;
while ($row = $db->nextRow($result)) {
$time = strtotime($row['hold_on']);
$curtime = time();
if(($curtime-$time) > $checkTimeInSeconds) { ///3600 seconds
$sql = 'UPDATE `'._DB_PREFIX_.'lopp_ticket`
SET
`id_customer` = 0,
`hold_on`=0,
`status` = 1
WHERE `ticket_id` = '.$row['ticket_id'];
if(Db::getInstance()->execute($sql)) {
echo $row['ticket_id'].' Updated'.'<br>';
}
}
else {
echo $row['ticket_no'].'No'.'<br>';
}
$i++;
}
So here do I need to close the db connection anywhere in the above code or PrestaShop will handle itself?
Because the server admin is saying too many database sessions are been opened by our code ,
Also Is there anyway to check from where too many db sessions are open/active always ?
As far as i know i never have closed a DB connection in Prestashop.
There documentation also does not explicitly state to close each DB request.
Looking into there source code they also never run a close command after a DB connection.
Looking into the classes\db\DbMySQLi.php class we can find the function below.
/**
* Destroys the database connection link.
*
* #see DbCore::disconnect()
*/
public function disconnect()
{
#$this->link->close();
}
Then we will look into classes\db\Db.php where we find that the function $this->disconnect() is called. So its safe to say they will close all there DB connections automatically.
/**
* Closes connection to database.
*/
public function __destruct()
{
if ($this->link) {
$this->disconnect();
}
}

Show missing dates inside loop even if they don't exist inside MYSQL

I have following mysql query
SELECT count(order_id), date FROM tbl_order WHERE campaign_status = 'In Progress' or campaign_status = 'Pending' GROUP BY DATE_FORMAT(date,'%d %b %y')
and then following loop
<?php do { ?>
['<?php echo $row_chartData['date']; ?>', <?php echo $row_chartData['count(order_id)']; ?>],
<?php } while ($row_chartData = mysql_fetch_assoc($chartData)) ?>
this loop is used to create data for my chart. Now the problem is that there are certain days that users dont make orders in my store so those dates are not stored inside database, so when I loop trough those dates are not showed in above results and inside the chart.
The question I have, is there any way to show those missing dates in loop above even if they dont exist inside mysql database.
Thanks for help.
Well, in this case, create a temporary array based on the date range, e.g. if you want to show the graph from May 1, to May 31.
Loop from 1 to 30,
set $data[i] = 0;
Now loop through the db records and set
$data['date'] = $row['count']
Yes.
Firstly make $row_chartData as array instead of a mysql_result.
1) find the min date in the range or whichever date you want to start with
function _getDate($row) {
return $row['date'];
}
$dates = array_map('_getDate', $row_chartData);
$minDate = min($dates);
2) find the max date in the range or whichever date you want to end with
$maxDate = min($dates);
$dateRangeArray = array();
$date = $minDate;
while($date < $maxDate) {
$dateRangeArray[] = $date;
$date = date('Y-m-d', strtotime($date . ' +1 day'));
}
3) make the key of each element in your $row_chartdata array be the value of the date index
foreach($row_chartData as $key => $row) {
$row_chartData[$row['date']] = $row;
unset($row_chartData[$key]);
}
4) iterate over each of the days in the range and match that date to the index in your $row_chartdata array
foreach($dateRangeArray as $date) {
if(isset($row_chartData[$date])) {
//do whatever
}
}

Freaking behaviour with Zend_Date and Cronjob

We have an Cron-Script, which detects - if some users got kicked out of our application.
We can detect this, if a specific value is 1 - but in the the stream, no new entries get set.
Scripts run every hour. Mostly non are detected. But since 2012-10-31 23:59:03 every user got detected. If i run the script on my local maschine or even on the same machine as the cron runs. Everything got handled as it should.
First things first, our script:
require_once ('cron_init.php');
ini_set('date.timezone', 'Europe/Berlin');
ini_set('max_execution_time', 30);
ini_set('memory_limit', -1);
error_reporting(E_ALL);
ini_set("display_errors", 1);
Zend_Date::setOptions(array('fix_dst' => true));
$userinfos = new Repricing_Dbservices_Userinfos();
$users = $userinfos->getUsersForRepricing();
$repricingstream = new Repricing_Dbservices_Repricingstream();
$error = new Repricing_Dbservices_Error();
if($users!==false AND count($users)>0){
$counter = 0;
$errCounter = 0;
$jetzt = new Zend_Date();
$jetzt->setTimezone('Europe/Berlin');
$jetzt = $jetzt->get(Zend_Date::TIMESTAMP);
foreach($users as $user){
$stream = $repricingstream->getStreamLimit($user);
$last = new Zend_Date($stream);
$last->setTimezone('Europe/Berlin');
$last = $last->get(Zend_Date::TIMESTAMP);
$diff = (($jetzt-$last)/60);
$error->setError(1, 'DIED', $diff, $user);
if($diff > 50 ){
$errCounter++;
$userinfos->setUserFree($user);
$error->setError(1, 'DIED', 'ANSTOSSEN', $user);
}
$counter++;
}
$error->setError(1, $errCounter, 'ANSTOSSEN_ALL', 'ALL');
}
Usually $diff >= 0 AND $diff <= 4 but, we detected, that $diff is always round about 381595. If we run it out of cron $diff is, as it should.
We also detected, that $jetzt is now ( as it should ) only $last is much more later. 381595 later. But that shouldnt be. The last stream-date is fully normal. We cant understand this behaviour of. Zend_Date with cron. Bevor 2012-10-21 23:59:03 the script run 2 weeks as it should. We cant explain, how come. Can you?
Consider this:
$right = new Zend_Date('2012-11-01 12:12:12', Zend_Date::ISO_8601);
var_dump( $right->getIso() ); // 2012-11-01T12:12:12+00:00
var_dump( $right->getTimestamp() ); // 1351771932
$wrong = new Zend_Date('2012-11-01 12:12:12', null, 'en_US');
var_dump( $wrong->getIso() ); // 2012-01-11T12:12:12+00:00
var_dump( $wrong->getTimestamp() ); // 1326283932
Now the real freaky part: on my PC it's the second behavior that is default - i.e., when no additional params are given to Zend_Date constructor.
The point is, Zend_Date is a bit... too helpful when trying to parse datetime strings. For example, it's taking the locale into account - but the locale both of server and client! And if the string cannot be parsed within this locale's rules, it silently gives up - and tries to use another rule.
That's why 2012-10-29 was parsed as October, 29 (despite of what locale suggested, as there's no 29th month) - but 2012-11-01 became January, 11 - and messed up your script big time. )