Skip to content
Advertisement

PHP MySQL loop through the rows and print date when the date changes

My messages table is like this:

This is my query used for fetching messages:

I want to use created_at timestamp field to group messages in such a way so that I can display date when the message transactions took place.

For example:

I therefore want to print a new header containing date each time the date changes. My current PHP loop goes like this:

Advertisement

Answer

Very simple. First you need to declare a null variable outside of the loop and then check the timestamp’s date against it and print the date. Then at the end you can update the previously defined null variable with the date from the timestamp and you are done. Have a look at the code below:

Done! As simple as that. Enjoy 🙂

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement