Shaik
Shaik

Reputation: 930

PHP Fetch Present Week data From MySQL

The below PHP code is working fine for the present date to fetch data from MySQL for attendance of a particular id defined. I need it to fetch for the present week and month. I have Googled a lot but unable to solve. Small help will be appreciated a lot.

In case if there is a possible way with JavaScript also please let me know.

// SELECT Time Zone
date_default_timezone_set("Europe/Belfast");

// SELECT Date With Default Time i.e  "00:00:00"

$date= date("y-m-d 00:00:00");

$mysqli=mysqli_connect('localhost','Uid','PASS','DB');  

//Passed From Ajax      
$Fetch_date = $_POST['ID'];

// Example Date is 2015-06-18 00:00:00 And id is 12345
$query ="SELECT * FROM attendance WHERE  RegID='$Fetch_date' And Date='$date' ";

$result = mysqli_query($mysqli,$query)or die(mysqli_error());

$num_row = mysqli_num_rows($result);

while($row=mysqli_fetch_array($result))
{
   //Echo result hear Working Fine
}

Upvotes: 1

Views: 234

Answers (2)

mariobgr
mariobgr

Reputation: 2201

This month:

$date1 = date('Y-m-01 00:00:00');
$date2 = date('Y-m-d 23:59:59', strtotime('last day of this month'));

$sql = "select * from attendance where RegID='$Fetch_date' and Date > '$date1' and Date < '$date2' ";

This week:

$date1 = date('Y-m-d 00:00:00', strtotime('monday this week'));
$date2 = date('Y-m-d 23:59:59', strtotime('sunday this week'));

$sql = "select * from attendance where RegID='$Fetch_date' and Date > '$date1' and Date < '$date2' ";

P.S.: This question has nothing to do with javascript.

Upvotes: 2

Dr.Molle
Dr.Molle

Reputation: 117314

You may use the mysql-date-functions:

$query ="SELECT * FROM attendance 
                  WHERE  RegID = '$Fetch_date' 
                  AND YEAR(Date) = YEAR(NOW()) 
                  AND MONTH(Date) = MONTH(NOW()) 
                  AND WEEKOFYEAR(Date) = WEEKOFYEAR(NOW())";

In Javascript you may test it the similar way, use getFullYear and getMonth. A function which returns the Week of the year is not available , but may use comparision based on Math.floor(MillisecondsOfTheDate/MillisecondsOfAWeek)

Upvotes: 2

Related Questions