I have a mysql database of entries with dates. So what I want is to show all the dates in my database and then under each date, I want to show all the entries in the database entered on the specefic date. I am thinking of two loops but I don't know how to write the condition to display all the dates in my database before I loop out the entries under that date.
Edit: i used NOW() to store the date. Using the loop by longneck, how can ignore the time when checking if date is sameas previous? Should I explode? What's the best way?
you should use one query, sort it by date, and detect the change in the date as a signal to display the next date:
<?php
$sql = 'select start_date, name from events order by start_date';
$res = mysql_query($sql) or die(mysql_error());
$prev_date = null;
while ($row = mysql_fetch_assoc($res)) {
if ($row['start_date'] != $prev_date) {
echo "<h1>{$row['start_date']}</h1>"\n;
$prev_date = $row['start_Date'];
}
echo "<p>{$row['name']}</p>";
}
?>
I'm assuming that you want a list of the dates so that you can then do separate queries for each date's entries. Usually you would use a query like:
SELECT DISTINCT date_field FROM table_name ORDER BY date_field DESC
(this will do it newest-first, remove DESC to make it oldest-first)
Now, you probably don't want to do it this way, because it will require a lot of queries (one for each day's entries). It is more efficient to just order the entries by the date, and then use logic in your php to print out the headers. So you would use code like:
$result = $db->query("SELECT * FROM table_name ORDER BY date_field DESC");
$current_date = "";
while ($row = $result->fetch_array()) {
if ($current_date != $row["date_field"]) {
echo "<h3>{$row['date_field']}</h3>";
$current_date = $row["date_field"];
}
// Print your entry from $row here.
}
you would probably want to get that in your SQL statement: (assuming it is datetime type)
SELECT * FROM table
WHERE date BETWEEN '2009-9-8 00:00:00' AND '2008-9-8
23:59:59'
Then just do your normal loop through your results
Also have a look at the GROUP BY clause of the SELECT statement.
Related
Im trying to display records in the current month from a column thats a timestamp.
This is my code
$query = "SELECT
donationid
FROM
donation
ORDER BY
donationid
WHERE
MONTH(donatedon) = MONTH(CURRENT_DATE())";
$query_run = mysqli_query($conn, $query);
$row = mysqli_num_rows($query_run);
echo '<h1>'.$row.'</h1>';
You're not checking the year, so you'll return records in the current month in any year, not just the current month.
Testing a function of a column prevents an index from being used to optimize the query. It's better to use a relational comparison if possible. You can simply create a formatted date for the beginning of the current month.
You also have ORDER BY in the wrong place, it has to be after the WHERE clause.
SELECT donationid
FROM donation
WHERE donatedon >= DATE_FORMAT(CURRENT_DATE(), '%Y-%m-01')
ORDER BY donationid
I am trying to get past fixtures for a football website. A user will add a fixture into the database and then I want the PHP script to return all fixtures that have a date older than or equal to today. This will then populate a drop-down to select the match and enter a score.
require 'connect-mysql.php';
$sql = $conn->query("SELECT
*
FROM
fixtures
WHERE
fixture_date <= " .date("Y-m-d"). "
ORDER BY
fixture_date DESC");
$rows = array();
while ($row = $sql->fetch_assoc()) {
$rows[] = $row;
}
echo json_encode($rows); // Parse to JSON and print.
The current output is nothing when I have database entries with a date of yesterday.
For example, I'd expect it to output a result if there was a fixture in there for today because I have put equal to also.
I want the PHP script to return all fixtures that have a date older than or equal to today.
Under most circumstances, you can probably trust that "today" for the user is the same as "today" on the database. There is no need to pass in the value. Just use curdate() or a similar built-in value:
SELECT f.*
FROM fixtures f
WHERE f.fixture_date <= curdate()
ORDER BY fixture_date DESC;
There's an error in your query, the quotes around the PHP date are missing. Try this:
$sql = $conn->query("SELECT
*
FROM
fixtures
WHERE
fixture_date <= '" .date("Y-m-d"). "'
ORDER BY
fixture_date DESC");
Better still: Check for MySQL errors.
I have a PHP script which users submit a post and saves in to the database; I'm storing the date it was posted using time(). I'm trying to figure out a way to filter my data by day. I have a while loop which is returning all the posts that user made which is ordered by date, however what I'm looking to do is have headings of a date for e.g. 10 December 2011 and only have posts that was submitted on that day. I want it only to display the heading if there is data for that day.
Thanks a lot.
EDIT:
Here is my while loop at the moment:
$get_posts = mysql_query( "SELECT * FROM `posts` WHERE `userid` = '$name[id]' ORDER BY `date` DESC" );
while( $userpost = mysql_fetch_assoc( $get_posts ) )
{
echo $userpost[ 'post' ];
}
But somehow before the loop I need to display the date heading the post or posts was submitted. I'm thinking it would need to be a loop outside of the current loop but I have no idea how to go about it.
As you have mentioned in one of your comments to the question that the DB column is of type integer. And so I assume you are storing the UNIX timestamp in the column. From what I understand, you are looking to display something like:
DATE HEADING 1
- data
- data
DATE HEADING 2
- data
- data
And if that is correct, this code snippet might help:
$rs = mysql_query('SELECT `column1`, `column2`, FROM_UNIXTIME(`the_time_column`, \'%d %M %Y\') AS `date_value`
FROM `your_table`
ORDER BY `the_time_column`');
$old = '';
while ($row = mysql_fetch_assoc($rs)) {
$new = $row['date_value'];
if ($new != $old) { // marks the beginning of a new heading
echo 'heading = ' . $new;
}
// start displaying data under the heading
echo $row['column1'];
echo $row['column2'];
// finish displaying data
$old = $new;
}
Please note that I've used dummy column and table names, so please replace them with the actuals. Also, the above snippet will display heading in ascending order of date. To show in reverse, add DESC at the end of the query.
Hope the above helps!
You get that right from the database, i.e.:
SELECT * FROM YourTable
WHERE
DAY(yourDateField)='15' AND
MONTH(yourDateField)='10' AND
YEAR(yourDateField)='2011'
;
or better yet, directly, like this:
SELECT * FROM YourTable
WHERE yourDateFieldld=2011-12-10;
Depends how you store the data in your DB.
In any case, this should be done in the database, not PHP
You could use BETWEEN.
Have a look at The MySQL Reference
Hey guys, I created a list for fixtures.
$result = mysql_query("SELECT date FROM ".TBL_FIXTURES." WHERE compname = '$comp_name' GROUP BY date");
$i = 1;
$d = "Start";
while ($row = mysql_fetch_assoc($result))
{
$odate = $row['date'];
$date=date("F j Y", $row['date']);
echo "<p>Fixture $i - $d to $date</p>";
}
As you can see from the query, the date is displayed from the fixtures table.
The way my system works is that when a fixture is "played", it is removed from this table. Therefore when the entire round of fixtures are complete, there wont be any dates for that round in this table. They will be in another table.
Is there anyway I can run an other query for dates at the same time, and display only dates from the fixtures table if there isnt a date in the results table?
"SELECT * FROM ".TBL_CONF_RESULTS."
WHERE compid = '$_GET[id]' && type2 = '2' ORDER BY date"
That would be the second query!
EDIT FROM HERE ONWARDS...
Is there anyway I can select the date from two tables and then only use one if there are matches. Then use the rows of dates (GROUPED BY) to populate my query? Is that possible?
It sounds like you want to UNION the two result sets, akin to the following:
SELECT f.date FROM tbl_fixtures f
WHERE f.compname = '$comp_name'
UNION SELECT r.date FROM tbl_conf_results r
WHERE r.compid = '$_GET[id]' AND r.type2 = '2'
GROUP BY date
This should select f.date and add rows from r.date that aren't already in the result set (at least this is the behaviour with T-SQL). Apparently it may not scale well, but there are many blogs on that (search: UNION T-SQL).
From the notes on this page:
//performs the query
$result = mysql_query(...);
$num_rows = mysql_num_rows($result);
//if query result is empty, returns NULL, otherwise,
//returns an array containing the selected fields and their values
if($num_rows == NULL)
{
// Do the other query
}
else
{
// Do your stuff as now
}
WHERE compid = '$_GET[id]' presents an oportunity for SQL Injection.
Are TBL_FIXTURES and TBL_CONF_RESULTS supposed to read $TBL_FIXTURES and $TBL_CONF_RESULTS?
ChrisF has the solution!
One other thing you might think about is whether it is necessary to do a delete and move to another table. A common way to solve this type of challenge is to include a status field for each record, then rather than just querying for "all" you query for all where status = "x". For example, 1 might be "staging", 2 might be "in use", 3 might be "used" or "archived" In your example, rather than deleting the field and "moving" the record to another table (which would also have to happen in the foreach loop, one would assume) you could simply update the status field to the next status.
So, you'd eliminate the need for an additional table, remove one additional database hit per record, and theoretically improve the performance of your application.
Seems like what you want is a UNION query.
$q1 = "SELECT DISTINCT date FROM ".TBL_FIXTURES." WHERE compname = '$comp_name'";
$q2 = "SELECT DISTINCT date FROM ".TBL_CONF_RESULTS.
"WHERE compid = '$_GET[id]' && type2 = '2'";
$q = "($q1) UNION DISTINCT ($q2) ORDER BY date";
I have a mysql database of entries
with dates. So what I want is to show
all the dates in my database and then
under each date, I want to show all
the entries in the database entered on
the specefic date. I am thinking of
two loops but I don't know how to
write the condition to display all the
dates in my database before I loop out
the entries under that date.
<?php
$sql = 'select start_date, name from events order by start_date';
$res = mysql_query($sql) or die(mysql_error());
$prev_date = null;
while ($row = mysql_fetch_assoc($res)) { if ($row['start_date'] != $prev_date) {
echo "<h1>{$row['start_date']}</h1>"\n;
$prev_date = $row['start_Date']; }
echo "<p>{$row['name']}</p>"; }
?>
In a previous question (Looping out mysql data), I resulted in using this code. It pulls the date and time from MYSQL, and I used NOW() to store both date and time. How can I make it ignore the time so I can achieve what I want?
as David Andres mentions in the comment, DATE() extracts the date part of a date or datetime expression. so you can do the following:
<?php
$sql = 'SELECT DATE(start_date) AS start_date_date, name FROM events ORDER BY start_date';
$res = mysql_query($sql) or die(mysql_error());
$prev_date = null;
while ($row = mysql_fetch_assoc($res)) {
if ($row['start_date_date'] != $prev_date) {
echo "<h1>$row[start_date_date]</h1>\n";
$prev_date = $row['start_date_date'];
}
echo "<p>$row[name]</p>";
}
Use CURDATE() instead of NOW().
Try it with a condition like this:
SELECT * FROM `events` WHERE DATE(`start_date`) = '2009-09-09';
This'll get you all events from the database for Sep 9th 2009. I think that's what you're asking for, is it?
Untested code that I will probably need someone to correct, but here goes:
SQL to retrieve all the dates that exist in the table:
$sql_get_dates = 'select start_date from events order by start_date distinct';
And, assuming start_date is a DATETIME type, the SQL to get all events on a given date:
$sql_get_events = 'select * from events where date(start_date) = "2009-08-09"';
Instead of just selecting the date, you could use some of the MySQL time functions to truncate the date.
$sql = "select date_format(start_date, '%Y-%m-%d') as fstart_date, name from events order by start_date";
Of course, you'll have to change start_date to fstart_date within the PHP code.
Check out the Mysql reference page for DATE_FORMAT().