Select records from today, this week, this month php mysql
To select records from today, you can use the following code:
$today = date('Y-m-d');
$query = "SELECT * FROM table WHERE date_column = '$today'";
To select records from this week, you can use the following code:
$week_start = date('Y-m-d', strtotime('last monday'));
$week_end = date('Y-m-d', strtotime('next sunday'));
$query = "SELECT * FROM table WHERE date_column BETWEEN '$week_start' AND '$week_end'";
To select records from this month, you can use the following code:
$month_start = date('Y-m-01');
$month_end = date('Y-m-t');
$query = "SELECT * FROM table WHERE date_column BETWEEN '$month_start' AND '$month_end'";
Watch a video course
Learn object oriented PHP
Replace "table" and "date_column" with the actual names of your table and date column, respectively.
To execute the query, you can use a MySQL function such as mysqli_query()
or PDO::query()
.
$result = mysqli_query($connection, $query);
// or
$result = $pdo->query($query);
You can then use a loop such as mysqli_fetch_assoc()
or PDO::fetch()
to process the results.
while ($row = mysqli_fetch_assoc($result)) {
// process the row
}
// or
while ($row = $result->fetch()) {
// process the row
}