how to fetch dates between result using PHP query [duplicate] - php

This question already has answers here:
How do I query between two dates using MySQL?
(12 answers)
Closed 6 years ago.
I am trying to fetch some data from database based on user entered month and year and table name.
From month and year I calculate from_date and to_date
but query is not working if I put dates between $from_date and $todate.
$tableName = $_REQUEST['tableName'];
$month = $_REQUEST['monthName'];
$year = $_REQUEST['yearName'];
// echo json_encode($tableName);
$tableName = json_encode($tableName);
//echo $tableName;
$from_date = date('Y-m-d',strtotime($year."-".$month."-01"));
//echo json_encode($from_date);
//$to_date = date('Y-m-d',strtotime($year."-".$month."-01"));
$to_date = date('Y-m-t', strtotime($from_date));
//echo json_encode($to_date);
$conn = new PDO("sqlite:../../assets/rule_data.db");
$conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//$sqlQuery = "select * from $tableName WHERE date >= '".$from_date."' AND date <= '".$to_date."' ";
//$sqlQuery = "SELECT * FROM $tableName WHERE v_cr_sysdate >= '".$from_date."' AND v_cr_sysdate <= '".$to_date."' ";
//$sqlQuery = "SELECT * FROM $tableName";
//$sqlQuery = "select * from $tableName WHERE date >= '".convert('$from_date','%d-%m-%y')."' AND date <= '".date($to_date)."' ";
$sqlQuery = "select * from $tableName WHERE date between '". date('Y-m-d', strtotime($from_date))."' ";
$sqlQuery .= " AND date <='". date('Y-m-d', strtotime($to_date))."' ";
$query = $conn->query($sqlQuery);
echo json_encode($query);
echo json_encode(["riskModules"=>$query->fetchAll(PDO::FETCH_ASSOC)]);
If I remove AND consition and keep only where date >= '$from_date' It will work but not with date range of from and to date.
Please help where I am wrong in giving AND query to where clasuse.

You can use BETWEEN clause to replace a combination of "greater than
equal AND less than equal" conditions.
Changes
$sqlQuery = "select * from $tableName WHERE date between '". date('Y-m-d', strtotime($from_date))."' ";
$sqlQuery .= " AND '". date('Y-m-d', strtotime($to_date))."' ";
(OR) Which Is Similar As
$sqlQuery = "select * from $tableName WHERE date >= '". date('Y-m-d', strtotime($from_date))."' ";
$sqlQuery .= " AND date <= '". date('Y-m-d', strtotime($to_date))."' ";
Syntax
SELECT column_name(s)
FROM table_name
WHERE column_name BETWEEN value1 AND value2;
Quick Links
mysql-between-clause
The SQL BETWEEN Operator

Related

Gettings records by cureent date,week, and month in php mysql not working

I am trying to get the records per current day, week and month in php mysql. The date column is of date type. The issue is here is that my week records and months records are getting same from below script. Here is my code, have a look.
public function getTodayComing(){
$connection = db::factory('mysql');
$sql = "select * from bookings,bookers where ";
$qualifier = ' bookings.booker_id = bookers.id
AND ((status ="'.AppGlobal::$bookingStatus['APPROVE'].'"
OR status ="'.AppGlobal::$bookingStatus['RESCHEDULED'].'"
OR status ="'.AppGlobal::$bookingStatus['RECONSULTED'].'")
AND date=DATE( NOW() ))
ORDER BY date ASC';
$sql. = $qualifier;
return $valuearray = $connection->getArray ($sql );
}
public function getWeekComing() {
$connection = db::factory('mysql');
$sql = "select * from bookings,bookers where ";
$qualifier = ' bookings.booker_id = bookers.id
AND ((status ="'.AppGlobal::$bookingStatus['APPROVE'].'"
OR status ="'.AppGlobal::$bookingStatus['RESCHEDULED'].'"
OR status ="'.AppGlobal::$bookingStatus['RECONSULTED'].'")
AND date > DATE_SUB(NOW(), INTERVAL 1 WEEK)) ORDER BY date ASC';
$sql. = $qualifier;
return $valuearray = $connection->getArray( $sql );
}
public function getMonthComing() {
$connection = db::factory('mysql');
$sql = "select * from bookings,bookers where ";
$qualifier = ' bookings.booker_id = bookers.id
AND ((status ="'.AppGlobal::$bookingStatus['APPROVE'].'"
OR status ="'.AppGlobal::$bookingStatus['RESCHEDULED'].'"
OR status ="'.AppGlobal::$bookingStatus['RECONSULTED'].'")
AND date > DATE_SUB(NOW(), INTERVAL 1 MONTH)) ORDER BY date ASC';
$sql. = $qualifier;
return $valuearray = $connection->getArray( $sql );
}
Aah, I just saw it I think
date > DATE_SUB(...)
should be
date BETWEEN CUR_DATE() AND DATE_ADD(CUR_DATE(), INTERVAL 1 ...)

How to group records by date when date is in UNIX Timestamp format?

I'm getting two dates from PHP form in the dd-mm-yyyy format.
(Say 01/06/2013 and 30/06/2013)
Now I'm using following code to display the datewise result among the date range as given above, but it's not working for me as the dates stored in DB are in UNIX Timestamp format(transaction_date bigint(12)). How should I display the datewise results then? Can anyone help me in resolving this issue?
if($form_data['from_date']!='' && $form_data['to_date']!='') {
$from_time = explode("/", $form_data['from_date']);
$to_time = explode("/", $form_data['to_date']);
$start_date = mktime( 0,0,0,$from_time[1],$from_time[0],$from_time[2] ) ;
$end_date = mktime( 23,59,59,$to_time[1],$to_time[0],$to_time[2] ) ;
$sql =" SELECT COUNT(*) `total count`, SUM(transaction_status = 'success') `success`, ";
$sql .=" SUM(transaction_status = 'inprocess') `inprocess`, SUM(transaction_status = 'fail') `fail`, ";
$sql .=" SUM(transaction_status = 'cancelled') `cancelled` FROM user_transaction ";
$sql .=" WHERE transaction_date >= '".$start_date."' AND transaction_date <= '".$end_date."' GROUP BY transaction_date ";
$this->mDb->Query( $sql);
$queryResult = $this->mDb->FetchArray();
}
Thanks in advance.
Use FROM_UNIXTIME(transaction_date) to get it as date type. Info
Make change in your last line of query and replace with below code:
$sql .=" WHERE DATE_FORMAT(transaction_date,'%d-%m-%Y') >= '".$start_date."' AND DATE_FORMAT(transaction_date,'%d-%m-%Y') <= '".$end_date."' GROUP BY FROM_UNIXTIME(transaction_date)";
And this link will be more helpful to you MySQL convert datetime to Unix timestamp.

mysql check if uid record exist for today based on timestamp else do an insert

Im trying to do a mysql check if a record from $uid exist from today based on $timestamp and if it doesnt then do an INSERT.
//EXAMPLE RECORD FROM TABLE VOTE
--- #vote_fb_uid# --- #vote_time#
665414807 1369219044
tjt
//STEP 1 - do a look up on $uid and check with timestamp $today
$timestamp = $this->time;
$date = date('Y-m-d', $timestamp);
$today = date('Y-m-d');
$sql = "
SELECT * FROM vote WHERE
vote_fb_uid = '$this->fb_uid',
WHERE vote_time = '$CHECK_IF_THERE_IS_AN_ENTRY_FROM_TODAY'";
$res = mysql_query($sql) or die( mysql_error());
//STEP 2 - If no records are found for today - then we do an INSERT
if($no_record_for_today) {
$sql = sprintf("
INSERT INTO vote(
vote_fb_uid,
vote_time)
VALUES ('%s','%s')",
mysql_real_escape_string($this->fb_uid),
mysql_real_escape_string($this->time));
$res = mysql_query($sql) or die( mysql_error());
}
Obviously im strugling with the SQL part for the look up - im wondering if there isnt some in-built SQL function to do this or similar?
to check if you had a vote in the last 24 hours :
SELECT *
FROM vote
WHERE vote_fb_uid = '$this->fb_uid'
AND FROM_UNIXTIME(vote_time) >= DATE_SUB(NOW(), INTERVAL 1 DAY)
if you want to limit to the same day (mean you are allowed to post at 2013.05.21 23:55 and 2013.05.22 00:05)
SELECT *
FROM vote
WHERE vote_fb_uid = '$this->fb_uid'
AND DATE(FROM_UNIXTIME(vote_time)) = DATE(NOW())
CURDATE()
Returns the current date as a value in 'YYYY-MM-DD' or YYYYMMDD format, depending on whether the function is used in a string or numeric context.
mysql> SELECT CURDATE();
-> '2008-06-13'
mysql> SELECT CURDATE() + 0;
-> 20080613
Try this:
$today = date('Y-m-d'); //change it to timestamp if you want in timestamp
$sql = "
SELECT count(*) as total FROM vote WHERE
vote_fb_uid = '$this->fb_uid' and
vote_time = '$today'";
$res = mysql_query($sql) or die( mysql_error());
if($res[0]['total'] < 1){
$sql = sprintf("
INSERT INTO vote(
vote_fb_uid,
vote_time)
VALUES ('%s','%s')",
mysql_real_escape_string($this->fb_uid),
mysql_real_escape_string($this->time));
$res = mysql_query($sql) or die( mysql_error());
} else{
//return error("custom","","Already Inserted.");
echo "already inserted";
}
Your $sql query have a syntax error, you have used two times clause WHERE the correct syntax to use two or more clauses in where is using AND to join them, to get only record wich don't have an entry for today you can use DATE_SUB with 1 day interval
SELECT *
FROM vote
WHERE vote_fb_uid = '$this->fb_uid',
AND vote_time <= DATE_SUB(vote_time, INTERVAL 1 DAY)

how to pass the php variable in Mysql select Query

$valid is An array and $createdon and $days are get the Date value from array.
My select query is not work with these date value of PHP variable please solve its.
function checkexpiretime($valid)
{
$db = &JFactory::getDBO();
foreach($valid as $validity)
{
echo $createdon=$validity->CreatedOn;
echo $days=$validity->days;
}
echo $query="SELECT * FROM jos_generatekey WHERE CreatedOn BETWEEN DATE_ADD('".$createdon."',".INTERVAL $days DAY.")". "AND CURDATE()";
$db->setQuery($query);
$checkexpire = $db->loadObjectList();
print_r($checkexpire);
return $checkexpire;
}
Query should be like this:
$query= "SELECT * FROM jos_generatekey WHERE CreatedOn BETWEEN DATE_ADD('".$createdon."',INTERVAL ". $days ." DAY) AND CURDATE()";

Retrieve data from mysql on date selection

$query = "select * from researchsub_form where flag='1' and date between '$date' and '$date1' ";
I have two input, date and date1, I have to show the data from database between the date 'date' and 'date1' of flag='1', for this I use a SQL query, but I want to show the data when I enter only one date input which is either 'date' or 'date1'
You can create your condition where in dynamic.
$query = "select * from researchsub_form where flag='1'";
if(isset($date) && isset($date1))
$condition += " and date between '$date' and '$date1'";
else if(isset($date))
$condition += " and date > '$date'";
else if(isset($date1))
$condition += " and date < '$date1'";
$query += $condition;
Or you can assign to date the smalles date (1753), to date1 the biggest (9999) when one of them is empty, but its not good.
select * from researchsub_form where flag='1' and (date between '$date' and '$date1' or date='$date' or date='$date1')

Categories