$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')
Related
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
I am trying to select the date in the field end_date that is less or equal to current date but did not work and my field end_date as the same date format(08-09-2014) data as current date below is my code thanks
$currentdate = date("d-m-Y");
$query1 = "SELECT * FROM location WHERE end_date <= '$currentdate'";
$result1 = mysql_query ($query1) or die('query error');
while( $line1 = mysql_fetch_assoc($result1)){
echo $line1['end_date'];
}
try this
SELECT * FROM location WHERE end_date <= DATE_FORMAT(CURDATE(), '%Y-%m-%d')
try with -
SELECT * FROM location WHERE end_date <= DATE_FORMAT(CURDATE(), '%d-%m-%Y')
$currentdate = date("Y-m-d");
$query1 = "SELECT * FROM location WHERE `end_date` <= '$currentdate'";
$result1 = mysql_query ($query1) or die('query error');
while( $line1 = mysql_fetch_assoc($result1)){
echo $line1['end_date'];
}
try this... must have in database date format;;
If your currentdate is independent of the system date (e.g. if you are operating over different timezones), and if, for some reason, your end_date is not a date type, then try this:
SELECT * FROM location
WHERE str_to_date(end_date, '%d-%m-%Y') <= str_to_date('$currentdate', '%d-%m-%Y')
where the format can be changed to match your inputs.
If you want to compare dates, then make sure you are comparing dates and not strings.
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.
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)
This question already exists:
SQL order by date, time [duplicate]
Closed 9 years ago.
I have table named notify with (seeker, donor, date) columns
the date column of type (datetime) and it stores the following format YYYY-MM-DD HH:MM:SS I'm trying to SELECT 1 record with the latest date from notify table and then compare the date with the current date and calculate the number of days between tow dates..
<?php
session_start();
$email = $_GET['email'];
date_default_timezone_set('Asia/Riyadh');
$time = date("Y-m-d H:i:s");
$note = "SELECT * FROM notify WHERE seeker='".$_SESSION['email']."'AND donor='".$email."' ORDER_BY `date` DESC LIMIT 1";
$st = $conn->prepare($note);
$st->execute();
if($found = $st->fetch(PDO::FETCH_ASSOC)){
$now = $time;
$old_date = strtotime($found['date']);
$dateif = $now - $old_date;
if(floor($dateif/(60*60*24)) >= 7){
echo "the difference between tow dates is 7 days or more";
} else { echo "difference between tow dates is less than 7 days";}
}
?>
the code is not working ! i have only one record in my notify table with this value in date 2013-04-22 09:15:47
First of all, you should use prepared statements like this:
$note = "SELECT *
FROM notify
WHERE seeker=:seeker AND donor=:donor
ORDER BY `date` DESC
LIMIT 1";
$st = $conn->prepare($note);
$st->execute(array(
':seeker' => $_SESSION['email'],
':donor' => $email,
);
Without the place holders you're still open to SQL injection.
Second, you can't compare a string with an integer in this way:
$now = $time; // string
$old_date = strtotime($found['date']); // integer
$dateif = $now - $old_date; // dunno?
You should compare apples with apples:
$seven_days_ago = strtotime('-7 days');
$old_date = strtotime($found['date']);
if ($old_date > $seven_days_ago) {
echo "difference between tow dates is less than 7 days";
} else {
echo "the difference between tow dates is 7 days or more";
}
Since your date column doesn't exist, there's no point in ordering by it. Also, you're exposed to SQL injection in the case where $_SESSION['email'] is not secured.
So, the correct form would be to use prepared statements, as well as order by the right column. (assuming PDO, you can use mysqli as well):
/** #var PDO $pdo - Assuming a PDO connection. */
$query = "SELECT * FROM `user` WHERE `ID` = :email ORDER BY `time` DESC";
$stmt = $pdo->prepare($query);
$stmt->execute(array($_SESSION['email']));
$result = $stmt->fetchAll(PDO::FETCH_ASSOC); //Get all results in an associated array form.
Jack's answer shows you how to use prepared statements correctly. Here is the code to simplify the date calculation using DATEDIFF().
$note = "SELECT *, DATEDIFF(NOW(), `date`) AS date_diff
FROM notify
WHERE seeker=:seeker AND donor=:donor
ORDER_BY `date` DESC
LIMIT 1";
$st = $conn->prepare($note);
$st->execute(array(
':seeker' => $_SESSION['email'],
':donor' => $email,
);
$row = $st->fetch(PDO::FETCH_ASSOC);
// do something with $row
If you are attching any variables to string then you need to concatinate them using dot and oder by will come after where condition and inside $_SESSION you missed quotes
$query = "SELECT * FROM user WHERE ID='".$_SESSION['email']."' ORDER_BY date, time";
For retrieving latest date from database please try executing following sql query
$query="SELECT * FROM user WHERE ID='".mysql_real_escape_string($_SESSION[email])."' ORDER_BY date,time desc limit 1";
In order to retrieve latest date you need to sort field for date in descending order
$note = "SELECT * FROM notify WHERE seeker=' ".$_SESSION['email']. " ' AND donor=' ".$email." ' ORDER_BY date DESC LIMIT 1";
have you try to order by desc? as shown bellow:
$note = "SELECT * FROM notify
WHERE
seeker=' ".$_SESSION['email']. " '
AND
donor=' ".$email." ' ORDER_BY date DESC LIMIT 1";
you forgot ` here around date. date is reserved word in mysql,
if you want to use it as column name place ` around it.
EDIT also you have extra space remove it
$note = "SELECT * FROM notify WHERE seeker='".$_SESSION['email']. "'
AND donor='".$email."' ORDER_BY `date` LIMIT 1";