我有一个类似
的mysql表id title date filename
-----------------------------------------------
1 Sample Title 2014-10-08 file.pdf
2 Sample Title1 2014-07-09 file1.pdf
3 Title 3 2014-07-04 file2.pdf
在此列表中,我必须按日期顺序按顺序排序,以便我能够在第一个位置获取最后一条记录。为此,我用了
select * from table_name ORDER BY STR_TO_DATE( CONCAT( date ) , '%Y-%m-%d' ) DESC
我的pblm是我必须每月安排他们作为标题的月份
2014年7月-----> {标题} 在此标题下,应列出2014年7月表格中的记录等。 请帮助解决问题。谢谢
答案 0 :(得分:1)
你走了:
<?php
define("01","January");
define("02","Feb");
define("03","March");
define("04","April");
define("05","May");
define("06","June");
define("07","July");
define("08","Aug");
define("09","Sept");
define("10","Oct");
define("11","Nov");
define("12","Dec");
$con = mysql_connect("hostname","username","password");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db('trial', $con) or die( mysql_error());
$sql="select * from experiment group by date desc";
$result=mysql_query($sql);
echo "<table border=1>";
echo "<tr><th>title</th>"."<th>date</th>"."<th>filename</th></tr>";
$last_value=null;
while($row = mysql_fetch_array($result))
{
$date=$row['date'];
$date_exploded = explode("-",$date);
$value = $date_exploded[1];
if($value == $last_value){
echo "<tr><td>".$row['title']."</td><td>" .constant($value).</td><td>".$row['filename']."</td></tr>";
}
else{
$last_value=$value;
echo "<tr><td><div>separator</div></td><td>separator</div></td><td><div>separator</div></td></tr>";
echo "<tr><td>".$row['title']."</td><td>" .constant($last_value)."</td><td>".$row['filename']."</td></tr>";
}
}
echo "</table>";
?>
根据您的样式格式随意更改分隔符div。 我使用的数据库名为'trial',我使用的表名为'experiment'
实验表架构是:
+----------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+----------+-------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| title | varchar(25) | YES | | NULL | |
| date | date | YES | | NULL | |
| filename | varchar(25) | YES | | NULL | |
+----------+-------------+------+-----+---------+----------------+
答案 1 :(得分:0)
$query = <<<__EOQUERY__
select concat(date_format(`date`, '%b'), ' ', year(`date`)) as `month`, `title`
from `books`
order by `date` desc
__EOQUERY__;
$connection = new MySQLi('localhost','root','calistoga','test');
$result = $connection->query($query);
echo "<table>";
$lastmonth = null;
foreach ($result as $row)
{
$month = $row['month'];
$title = $row['title'];
if ($month !== $lastmonth)
{
echo "<tr><th>{$month}</th>";
$lastmonth = $month;
}
else
echo "<tr><td></td>";
echo "<td>{$title}</td></tr>";
}
echo "</table>";
此处使用的表定义:
create table `books` (
`id` integer not null auto_increment,
`title` varchar(255) not null,
`date` date not null,
`filename` varchar(255),
primary key (`id`)
) engine=InnoDB;
insert into `books` (`title`,`date`,`filename`)
values
('sample title1', '2014-12-31', 'file1.pdf'),
('sample title2', '2014-11-30', 'file2.pdf'),
('sample title3', '2014-11-24', 'file3.pdf'),
('sample title4', '2014-10-20', 'file4.pdf');