How to Search Between Two Dates With PHP & MySQL Code
After you use PHP functions to connect to the MySQL database, you can submit a query through the Web page to select data between two dates, provided the table you query has a "date" field. To use dates as a criteria, enter dates in the query using the "YYYY-MM-DD" format. Use an HTML form to prompt the user for two dates, or provide them yourself in the PHP code. How you format the returned data varies based on what you need it for.
Instructions
-
-
1
Open the HTML file, and insert the cursor where you want to search between two dates.
-
2
Type the following code:
<?php
$db = mysql_connect ('database_host_server', 'username', 'password');
mysql_select_db ('database_name);
Change the values of the arguments to those belonging to your database. These lines connect to your MySQL database.
-
-
3
Type the following code:
$query = mysql_query("SELECT * FROM table_name WHERE date >= 'earlier_date' AND date <= 'later_date';");
while($row = mysql_fetch_row($query)) {
echo "<p>Date for record is $row[index_of_date_field]</p>\n";
}
?>
Provide two dates in the query. For example, to search between June 1, 2011 and June 31, 2011, use '2011-06-01' and '2011-06-30' for the two values, respectively. Also, provide the index of the date field in your MySQL table for the $row variable's index. For example, if the date field is the first field in the table, use "$row[0]." If it's the second field, use "$row[1]."
-
4
Save the HTML file, then upload it to your server.
-
1