I have some data in my table which are [name][address][phone_number] and the date in this format 2015-10-14 14:37:38. I am using php PDO. How can I query out just today date from the table?
The following code is my code to query out result for the past 7 days which worked perfectly. However, whenever I replace it with 1 it doesn't work:
$query = $digital->query('SELECT * FROM sales WHERE `datetime` BETWEEN DATE_SUB(NOW(), INTERVAL 7 DAY) AND NOW() ORDER BY sale_id DESC');
What I want is to be able to query out all today data inserted into database.
You can use this, haven't tested.
<?php
$todaysDate = date('Y-m-d'); //if your date is stored in y-m-d format
try
{
$s = $conn->query("SELECT * from sales where datetime LIKE '%$todaysDate%'");
}
catch(PDOException $e)
{
echo $e->getMessage();
}
$results = $s->fetch(PDO::FETCH_OBJ);
?>
Your query results is now in $results variable.
Extended version
<?php
try
{
$s = $conn->query("SELECT * from sales");
}
catch(PDOException $e)
{
echo $e->getMessage();
}
while($results = $s->fetch(PDO::FETCH_OBJ))
{
$date = explode(" ", $results->datetime);
if($date[0] == date('Y-m-d'))
{
//write code here to display data
}
}
?>
Make sure you replace all the columnNames and tablename.
Edit :-
Here's a sqlfiddle pertaining to my first solution.
http://sqlfiddle.com/#!9/7c2f1/3
I dont know whether it applies to PDO, as I'm not very acquainted to it, but I use to pass the date in a var, then ask for a match in my sql statement
// choose your own timezone here
date_default_timezone_set('America/Sao_Paulo');
// then define your variable as the current time:
$date = date("Y-m-d H:i:s");
then, i'd use the correct PDO syntax to compare the column with the var (a simple "where" statement should do it).
(using codeigniter syntax)
$this->db->where('date', $date);
Related
I have in my MSSQL database a column with datatype of datetime which contains some dates in this format 2021-01-11 19:58:04.277.
This is a voting system, the idea is that the users can only vote once every 24 hours.
Every time they vote this table is updated with a new record and a new date is added with the corresponding user.
I want to display a message that says how many hours left to place the next vote.
This is the code I am trying to use:
/**
* Get Votes Time
*
*/
public function getVoteRemainingTime($account) {
date_default_timezone_get();
$currentTime = date('Y-m-d H:i:s');
$sql = "SELECT VoteDate FROM dbo.vote WHERE Account = :account ORDER BY logid DESC";
$query = $this->db->prepare($sql);
$query->execute(array(':account' => $account));
$voteDate = $query->fetch(PDO::FETCH_OBJ);
$timeLeftVote = strtotime($currentTime) - strtotime($voteDate->VoteDate);
if($timeLeftVote > 86400) {
return '<strong>Vote Available!</strong>';
} else {
return $timeLeftVote;
}
}
But it is displaying the wrong information. What I am doing wrong? I would appreciate your help.
Thanks!
you need declare format parameter of the date() like date('Y-m-d H:i:s')
date_default_timezone_get();
$currentTime = date('Y-m-d H:i:s');
$timeLeftVote = strtotime($currentTime) - strtotime('2021-01-11 19:58:04.277');
if($timeLeftVote > 86400){
echo 'Vote available';
}else{
echo $timeLeftVote;
}
Instead of SELECT VoteDate FROM dbo.vote
Can you do the calculation on the time difference at source in the database using
SELECT VoteDate, DATEDIFF(HOUR, VoteDate, GETDATE()) as HourDifference from dbo.vote
As I cannot check your database query, I only checked the rest of the code and it seems to work (as Fikri F mentioned in the comments of this post) if I replace $voteDate->VoteDate by a static date.
So please provide more information. You could output the current time and the previous vote time from the database as strings, and for both dates as well the result of strtotime, and in the end the result of the method. Then please explain, what the wrong behaviour is. By this, we can narrow down the problem either to the DB query or to the PHP code.
(I would write this as a comment, but I have not enough reputation.)
I want to send a reminder to my subscribers a month before their subscription ends, i have columns validity and reminder (type VARCHAR) in my MYSQL DB
date stored in those columns are saved using php date function
$validity = date('d/m/Y',strtotime("6 months"));
$reminder = date('d/m/Y',strtotime("5 months"));
now i want to send a mail when the current date is equals reminder date
I have a test entry with reminder value 22/06/2017 and $date variable echo the same value.
$date = date('d/m/Y');
$q = 'SELECT * FROM subscriptions WHERE reminder = "$date"';
$r = mysql_query($q);
if(!$r){
echo 'query err';
}
$a = mysql_num_rows($r);
echo 'No of rows returned '.$a;
*mailing script after this line*
this script outputs No of rows returned 0
Can someone give me some idea how i should approach this
First i suggest you your date format is change in database and type change datetime.
This format follow for you insert reminder date
$reminderdate = date('Y-m-d');
Then compare with currentdate when fetch data from database:
$date=date('Y-m-d');
if($r['reminder']==$date)
{
echo 'Mail sent here';
}
else
{
echo 'date not match';
}
Your script is at risk for SQL Injection Attacks, see this
The issue is here:
'SELECT * FROM subscriptions WHERE reminder = "$date"';
change it to:
"SELECT * FROM subscriptions WHERE reminder = '".$date."'";
to compare date, you have to wrap it into single quotes '
A few suggestions:
the reminder column may be redundant depending on your logic
in the future please use different approach to connect to the database, for example: http://php.net/manual/en/mysqli.quickstart.prepared-statements.php
the validity column should rather be DATETIME format
Now to your main question - it can be because of datetype mismatch so switch in database to DATETIME and in PHP use date('Y-m-d').
First Of all You should not store date in varachar.
Now to compare dates in varchar first you have to convert the string(varchar) into date.
for that you can use mysql's function:
str_to_date
You can get the example how to convert it and then compare it to get the result.
$q = "SELECT * FROM subscriptions WHERE reminder = '{$date}'";
I Know You have selected the answer already and ignored the comments, because you just want to get this done with and move on no matter how you did it. I will just make this answer a community WIKI.
Below are the things you need to note :
The API that you are using have depreciated for a long time ago rather use mysqli or even better PDO with prepared statements.
Also What I'm sure when the use subscrips on your website, you should have a column that stores the duration of the subscription and the actual expire date and a flag to identify expired subscriptions.
Mysql does provide its own date time functions, which you can use and use the date type on these columns.
Use API that is still active and maintained that is mysqli_* or pdo they both support prepared statements.
$host = '127.0.0.1';
$db = 'DBNAME';
$user = 'root';
$pass = '';
$charset = 'utf8';
$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$opt = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false
);
$dbh = new PDO($dsn, $user, $pass, $opt);
$stmt = $dbh->query("SELECT * FROM subscriptions WHERE subscriptionsExpireColumn = DATE_ADD(CURDATE(), INTERVAL 1 MONTH)");
if (!$stmt) {
echo "\nPDO::errorInfo():\n";
print_r($dbh->errorInfo());
} else {
$results = $stmt->fetchall();
if (count($results) > 0) {
foreach ($results as $row) {
//DO WHAT EVER YOU WANT TO DO WITH THE RESULTS
}
} else {
echo "no records found";
}
}
?>
I'm trying to SUM() my Elapsed column in an SQL query, but the datatype for my Elapsed column in the SQL database is text, and I am unable to change it. My attempt is below, but I continue to receive "failure".
<?php require 'dbcon.php'; ?>
$elapsed = "SELECT SEC_TO_TIME( SUM( TIME_TO_SEC( `STR_TO_DATE(Elapsed,'%d,%m,%Y') ) ) ) FROM Picks";
$s = $con->prepare($elapsed);
//$s->bind_param();
$s->execute();
$results = $s->fetchAll(PDO::FETCH_ASSOC);
if ($results){
foreach($results as $result){
foreach($result as $val){
echo $val;
}
}
}
else {
echo "failure";
}
THe Elapsed column in the SQL database looks like this-Datatype as display in a datatable table
If there is more information I forgot that would be helpful, don't hesitate to ask. Thanks!
It seems that you're getting a NULL value from your query. The issue is in your STR_TO_DATE declaration; you're using
STR_TO_DATE(Elapsed,'%d,%m,%Y')
These look for day month and year values. Try using %H,%i,%s, which look for hours minutes and seconds, which is how your Elapsed column is formatted according to your picture.
I am trying to get all rows in a database which have been created between two dates inclusively. When I search for meetings in 2013-05-01 and todays date, I get no results but when I search without the WHERE clause I see there are two records for today. I thought, since the dates are DATETIME, I would try casting them as dates but this doesn't seem to work.
My function is as follows:
function meeting_reports($connection, $to, $from)
{
$status = array();
$sql =
$connection->query (
"SELECT `meeting_id`,`visibility`,`meeting_start`
FROM `details`
WHERE DATE(`meeting_start`) BETWEEN '{$from}' AND '{$to}'"
);
$status["total_meetings"] = 0;
$status["cancelled_meetings"] = 0;
if($sql->num_rows > 0)
{
while($results = $sql->fetch_assoc())
{
if($results["visibility"]==0)
{
$status["total_meetings"]++;
}
elseif($results==1)
{
$status["total_meetings"]++;
}
elseif($results["visibility"]==2)
{
$status["total_meetings"]++;
}
elseif($results["visibility"]==3)
{
$status["cancelled_meetings"]++;
}
}
}
return $status;
}
What am I doing wrong?
I see a couple issues here.
you need to clarify if your data type is date, or datetime. going to assume datetime.
also if you are looking for meetings that occurred on a single specific day,
you cannot search for events between x and y if x=y. there is nothing between
it. if you are using datetime date type, concat 00:00:00 to your start date
and 23:59:59 to your end date, now you have a valid range that includes the the valid times for the date in question. or for single date searches, do between ? and ? + interval 1 day and pass date twice as '12-25-2015 00:00:00'
also, you are directly using strings in your query, this can open you up to
sql injection attacks. do a google search on bound parameters and never use
a variable in an sql query EVER again.
Try this
$connection->query (
"SELECT meeting_id,visibility,meeting_start
FROM details
WHERE meeting_start BETWEEN '" . $from . "' AND '" . $to . "'"
);
Trying to figure out why my code isn't working. Basically I have an elseif statment like so:
mysql_connect("localhost","xxxx","xxxxx");
mysql_select_db("xxxxxx");
$sql = "SELECT COUNT(DATE) FROM calendar";
$result = mysql_query($sql);
$row = mysql_fetch_assoc($result);
$checkdate = $row['DATE'];
$DATEFROM = $_POST['DATEFROM'];
$DAYCOUNT = $_POST['DAYCOUNT'];
$DAYS = $_POST['DAYS'];
if ( $DAYCOUNT < $DAYS ) {
header( 'Location: request_go_fail.php' );
}
else if ( $checkdate == $DATEFROM ) {
echo "FAIL!";
}
else {
It doesn't work, the first check (to see if the DAYCOUNT is less than DAYS works fine, but when comparing to entries in the DB it doesn't seem to do it. Seems to be some issue with finding the already existing data, as when I change $checkdate to an entry that's already in the database it works great.
Any help is most appreciated :)
SELECT COUNT(DATE) FROM calendar doesn't return a field called date, print_r the $row variable to confirm that. Best solution is to change the statement to something like SELECT COUNT(DATE) AS datecount FROM calendar and then do $checkdate = $row['datecount'];
But while rereading your code fragment, I'm not sure that you really want the count of DATE's in the calendar table, and what exactly the intention is, is hard to determine from the code fragment.
Also, DATE is a reserved word in SQL, not the optimal choice for a column name!
Did you try printing $checkdate? I suspect it's null if that is indeed the SQL you're using.
Should be $row['COUNT(DATE)'] I believe, or you can use mysql_fetch_array and $row[0] instead, or use an AS in your SQL or
$checkdate = mysql_result($result, 0);
And skip the fetch call all together.
COUNT(DATE) will return the number of non-null DATE fields in your DB btw, is that really what you want?
You don't have a DATE key in the $row variable because of the sql command. Use this instead, it's called Alias:
SELECT COUNT(DATE) AS DATE_COUNT FROM calendar
Now you have a key DATE_COUNT which will contains value.
$checkdate = $row['DATE_COUNT'];