automatic query

Ask about general coding issues or problems here.

Moderators: egami, macek, gesf

Post Reply
acellec
php-forum Active User
php-forum Active User
Posts: 26
Joined: Thu May 17, 2012 5:44 pm

Tue Jul 10, 2012 5:01 pm

Can you help me how to automatically query a table?

For example, if a user opens my website. It will query a particular table depending on the present month and year.

if the month and year today is july. It will automatically query and display all records in july 2012.
Please Help???? i need it today. :(
User avatar
simplypixie
php-forum GURU
php-forum GURU
Posts: 300
Joined: Sun Dec 11, 2011 12:51 am
Location: Shrewsbury, Shropshire
Contact:

Tue Jul 10, 2012 10:18 pm

Presuming you have a date field in your table:

Code: Select all

$sql = mysql_query("SELECT * FROM table WHERE date='".date('Y-m-d')."'");
while ($result = mysql_fetch_array($sql)) {
// Do stuff here
}
Put this code at the top of your page (unless you are using classes), format it to run as you need (in a while loop etc, what I have put is just an example) and do what you need to do with it. It will run when the page loads.
kyle04
php-forum Fan User
php-forum Fan User
Posts: 94
Joined: Sat Jul 07, 2012 1:36 pm

Wed Jul 11, 2012 3:45 pm

You may need to format the date to match your table records, eg if the table dates are formatted as :
12 July 2012, or July 12 2012 the corresponding date format will work :
So to display results as a table, with 3 fields :

$DISPLAY .= "<table width=100% border=1>\n";


$month_year = date("M Y"); // today - no day needed for month - year display only

$sql = mysql_query("SELECT * FROM table");
while($row = mysql_fetch_array($result)) {

$var1 = $row['field1'];
$var2 = $row['field2']; // etc
$date = $row['date_field'];

$newdate = new DateTime($date);
$d = $newdate->format('M Y'); // format date to month and year only

if($d==$month_year) { // if dates match show the records
$DISPLAY .= "<tr>";
$DISPLAY .= "<td>".$var1."</td><td>".$var2."</td><td>".$d."</td>";
$DISPLAY .= "</tr>";

}// if
}// while

$DISPLAY .= "</table>";

echo $DISPLAY;

AndyP
Post Reply