开发者

PHP MySQL Date comparison

开发者 https://www.devze.com 2023-01-23 20:55 出处:网络
I insert a birth date through a text field into a table. Here I need a mysql query which checks the current month and current date with any of the dates matching in database.

I insert a birth date through a text field into a table. Here I need a mysql query which checks the current month and current date with any of the dates matching in database. No need to check the year because this is meant for displaying an alert on birthday, Can any one have the idea of the SQL Query to do this in a single query.. Her开发者_运维问答e I use this with PHP and MySQL. Thanks in Advance

My Sample Code is :

<?php
$con = mysql_connect("localhost","root","");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

mysql_select_db("test", $con);

$my_birth_date = "2010-11-08";

$result = mysql_query("SELECT * FROM mydate WHERE DAYOFMONTH($my_birth_date) = DAYOFMONTH(NOW()) AND MONTH($my_birth_date) = MONTH(NOW())
");


while($row = mysql_fetch_array($result))
  {
  echo $row['my_name'] . " " . $row['my_dob'];
  echo "<br />";
  }

mysql_close($con);
?> 

My Table Schema is: my_name varchar(50) my_dob date

Date is being stored in table like this format : 2010-01-20 (Year-Month-Day) Now it is displaying a blank page with out any records, even if i has records matching. Can any one give some suggestion


http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html

You can find all the Date & Time Functions available in MySQL. You'd probably want to use the DAYOFMONTH and MONTH functions to compare :)

So something like:

SELECT * FROM table WHERE DAYOFMONTH(birthday) = DAYOFMONTH(NOW()) AND MONTH(birthday) = MONTH(NOW())

There might be some more efficient ways to do this but this is what I'd try first! Hope that helps!


Your sample code should return all the records in the "mydate" table.

Try the query directly on the server(in a terminal or with an app like phpMyAdmin) to check if it returns data.

Use mysql_error to debug your code.

Example :

<?php
$link = mysql_connect("localhost", "mysql_user", "mysql_password");

mysql_select_db("nonexistentdb", $link);
echo mysql_errno($link) . ": " . mysql_error($link). "\n";

mysql_select_db("kossu", $link);
mysql_query("SELECT * FROM nonexistenttable", $link);
echo mysql_errno($link) . ": " . mysql_error($link) . "\n";
?>

mysql_error : php.net.

Then you should see where it crash.

0

精彩评论

暂无评论...
验证码 换一张
取 消