Jump to content

Pulling data from mysql database (this today/week/month)


ukscotth

Recommended Posts

Hi,

 

I have a table that contains posts and each post has a datetime field.

 

Im trying to work out how I can show entries from today, this week and this month so I can have a link that shows all posts from today or this month etc.

 

Any one know how I can do this ? My current piece of code that pulls the data from the db looks like this :

 

$texts= mysql_query("SELECT * FROM submittedtexts Order by id DESC LIMIT " . (($page - 1) * 6) . ", 6");

 

I want to add a bit that acts like : WHERE date = today

 

 

Hope that makes sense, Im a bit of a newbie :(

 

Thanks in advance,

 

Scott

sure.

 

Basically it just pulls the data from the database and displays it :

 

$texts= mysql_query("SELECT * FROM submittedtexts Order by id DESC LIMIT " . (($page - 1) * 6) . ", 6");

while ($got_texts = mysql_fetch_array($texts)){the code that simply displays the data}

You really don't want to use the PHP date function for this if you can avoid it. MySQL has time/date functions built-in HERE that are faster and more efficient. In what format are you storing the date? Is it in a DATE or DATETIME type data field? If it is, for today's date:

 

// if the field is DATETIME . . .
SELECT field1, field2 FROM table WHERE some_field = 'some_value' AND DATE(date_field) = CURDATE()

// if the field is DATE . . .
SELECT field1, field2 FROM table WHERE some_field = 'some_value' AND date_field = CURDATE()

 

Then you can add a BETWEEN clause in conjunction with MySQL's DATE_SUB() to get the last 7 days, or last month, etc.

 

SELECT field1, field2 FROM table WHERE some_field = 'some_value' AND date_field BETWEEN DATE_SUB( CURDATE(), INTERVAL 7 DAY ) AND CURDATE()

  • 4 weeks later...

thanks very much for the replies and sorry for the slow reply.

 

That looks great but instead of grabbing the last 7 days I need it to grab data from this week so it would be all posts since Monday. If that makes sense.

 

Would that be easy to do ?

 

Thanks again.

 

Scott

Seems to work great. Sorry for being stupid but will this return posts from today or posts from this week ?

 

$sql = 'SELECT * FROM `submittedtexts` WHERE approved = 1 AND `date` > DATE_SUB(CURDATE(), INTERVAL WEEKDAY(CURDATE()) DAY) Order by id DESC LIMIT '. (($page - 1) * 6) .', 6';

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.