1

I have a field in the database called date where the content is: 29/07/2014

Now, I'm trying to return how many fields have today's date and I actually know that there's 1.

This is my query:

$result = mysqli_query($con,"SELECT * FROM mytable WHERE `date` = date('d/m/Y') ");

$totalToday=mysqli_num_rows($result);

Why is $totalToday return 0 when it should be returning 1 ? Syntax ?

7
  • Are you able to fetch any record by your query itself? Commented Jul 29, 2014 at 16:00
  • 1
    @RonakPatel $result is not an array, it's a mysqli_result object. Commented Jul 29, 2014 at 16:00
  • 2
    You can't put function calls in strings like that. The query executed is probably trying to match against any dates that are literally "date('d/m/y')" Commented Jul 29, 2014 at 16:01
  • 2
    date('d/m/Y') << that is a PHP date function. It is recommended to change your table so that the date column is a real MySQL DATE type, rather than a string. However, you can get the date formatted that way in MySQL with DATE_FORMAT(CURDATE(), '%d/%m/%Y') Commented Jul 29, 2014 at 16:01
  • In the spirit of OOP, use $result->num_rows. Not that it solves the problem, though. Commented Jul 29, 2014 at 16:06

2 Answers 2

2

Your issue lies in your query:

$result = mysqli_query($con,"SELECT * FROM mytable WHERE `date` = date('d/m/Y') ");

Your query string literally means "Take every column from mytable where the date field is equal to the evaluation of the MySQL date function with the input 'd/m/Y'."

In order to get the date function from PHP evaluated into your query string, you need to evaluate it separately:

$result = mysqli_query($con,"SELECT * FROM mytable WHERE `date` = '" . date('d/m/Y') . "'");
Sign up to request clarification or add additional context in comments.

Comments

2

The MySQL function for formatting dates is DATE_FORMAT. The first argument is the time to format, the second argument is a format string, and the formatted elements are prefixed with @.

$result = mysqli_query($con,"SELECT * FROM mytable WHERE `date` = date_format(NOW(), '@d/@m/@Y') ");

5 Comments

Doesn't answer the question.
Why doesn't it? Since he was using the wrong function, his query wasn't matching anything, so he got 0 rows. Using the correct function fixes that.
Okay, your edit means it will work now. The original version didn't answer the question.
Why didn't you say that the problem was that I left out an argument? I had the right approach, I just made a small mistake.
Because I wasn't aware of the correct syntax myself until I saw your fix. :) I just thought you'd given one invalid query to replace another one

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.