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";
}
}
?>
Related
im trying to select date from mysql between dates with this code
if(isset($_REQUEST['datefrom']) and $_REQUEST['datefrom']!=""){
$condition .= ' AND date LIKE "%'.$_REQUEST['datefrom'].'%" ';
}
if(isset($_REQUEST['dateto']) and $_REQUEST['dateto']!=""){
$condition .= ' AND date LIKE "%'.$_REQUEST['dateto'].'%" ';
}
Please help
THX
Assuming your date are timestamps, date, etc.
This is the most secure way to prevent SQL injection, using PHP PDO.
<?php
$dbh = new PDO('your_server', 'your_user', 'your_password');
$sth = $dbh->prepare('SELECT * FROM table WHERE date BETWEEN :from AND :to');
// Bind date params
$sth->bindParam('from', $_REQUEST['datefrom']);
$sth->bindParam('to', $_REQUEST['dateto']);
// Execute query
$sth->execute();
// This a test
print_r($sth->fetchAll());
?>
More here.
It seems you are trying to use the LIKE operator because your dates are stored as strings in your database.
You should convert them to dates, then you can just use the BETWEEN operator with them. It shouldn't be too dificult and I'm sure you can find how to do it in this site. I suggest that you do it by storing the conversion in a new column first.
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);
I'm trying to add values to an array after getting data from a mysql query, this obviously involved a while ($x = mysql_fetch_array($MysqlQuery)) {} as seen below:
$CheckTime = mysql_query("SELECT * FROM cp11641_timetable.booking");
$dates = array();
while ($date = mysql_fetch_array($CheckTime)) {
$DateInt = strtotime($date['Date']);
//echo $DateInt . " ";
$dates[] = $DateInt;
echo $dates[1] . " ";
}
However when I echo $dates[x], it'll display the value in the x position of the array, but it'll show it by (x+1) times (i.e. $dates[0] will show 'a' once, $dates[1] will show 'b' twice, and $dates[2] will show 'c' thrice)
How do I fix this? What's causing the problem?
$CheckTime = mysqli_query($mysql_connection, "SELECT * FROM cp11641_timetable.booking");
$dates = array();
while ($date = mysqli_fetch_assoc()($CheckTime)){ // Use mysqli_* for queries.
$DateInt = strtotime($date['Date']); // This will show an UNIX timestamp
$dates[] = $DateInt; // Fills the array with the timestamp.
}
Your problem is that you use mysql_fetch_array. But then try to use $date['Date']. If you want to use the column names as indices in the $date array. You need to use mysql_fetch_assoc().
On a different note and as mentioned in the comments use the mysqli_* extension or PDO. In this answer I've used mysqli_*
Please note the $mysql_connection in the mysqli_query function.
MySqli Query Doc
Most likely if you use the code below it should work as intended.
Still strongly advise to switch to mysqli_*
$CheckTime = mysql_query("SELECT Date FROM cp11641_timetable.booking");
$dates = array();
while ($date = mysql_fetch_array($CheckTime)){
$DateInt = strtotime($date[0]);
$dates[] = $DateInt;
}
foreach($dates as $timestamp){
echo $timestamp . '<br/>';
}
This works, make sure to put in your correct credentials to connecting to your database on step #1. everything else false in place.
<?php
/* ==============================================
This is the new way of connecting to database
using mysqli
================================================*/
// Step #1 create credentiasl for database connection
$host = ""; //type your host ex. localhost between the quotes
$user = ""; //your username between the quotes
$pass = ""; //your password between the quotes
$db = ""; //your database you are connecting to between the quotes
// step #2 create connection to database
$conn = new mysqli($host, $user, $pass, $db);
//step #3 check and see if connection is working and error free
if ($conn->error) {
die("Could not connect to the database");
} else{
// create array dates
$dates = array();
// create select statement
$CheckTime = ("SELECT * FROM cp11641_timetable.booking");
// query the the database using the connection
$sql_CheckTime = $conn->query($CheckTime);
// if rows available in table add them to array dates
while ($row = mysqli_fetch_assoc($sql_CheckTime)) {
$dates[] = $row;
}
//optional uncomment bottom line to check if dates array has data will display as array on webpage
// var_dump($dates);
// loop through array
foreach ($dates as $date){
// echo out data you want to display. 'Date' = column name
echo strtotime($date['Date']) . "<br>";
};
};
?>
I recommend you to using mysql_fetch_assoc() and then display the dates horizontally or vertically with html/css style.
Sorry if my answer is bad choose.
I have a database which id,title,subject and datetime and I'm calling a php page that takes in a request from clients to show the latest entry in the db from the difference of time from the client and checks with the last entry's datetime. PHP code as follows
$date = "2012-10-06 18:13:52";
//Establish a connection
$conn = mysql_connect('localhost','regadmin','regadmin');
//Select the mySQL db
$db = mysql_select_db('easy_comm', $conn);
$sql = mysql_query("SELECT `title`, `subject`,`date_sent` FROM `books` WHERE `date_sent` > '$date'", $conn);
$count=mysql_num_rows($sql);
if($count != 0){
$json = array('boolean' => true);
}
else{
$json = array('boolean' => false);
//echo "No record";
}
From the above code and the provided $date variable, it will always return true and the last entry is
2012-10-06 18:10:52
I have tried converting to UNIXTIMESTAMP but same problem
Well this works good enough for me.Please make sure the column against which you are comparing the date surely happens to be DATETIME column not a VARCHAR or something else.
Please post us database structure to see the collation as well and also try printing the query on the fly and then execute in your console.
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'];