我是PHP新手。我已经编写了在目录中显示文件的代码,我需要按照修改日期(即上传日期)对文件进行排序,以显示修改过的文件在列表的顶部
这是我的代码
<?php
$path = $dpath.$lpath;
if ($handle = opendir($path)) {
while (false !== ($file = readdir($handle))) {
$dbfname = $path.$file;
if ($file != "." && $file != "..") {
$sql = "SELECT uploader, course FROM assignments WHERE filename = '$dbfname'";
$result = $conn->query($sql);
$row = $result->fetch_assoc();
// echo '<a href="/prac/admin/">'.$file.'</a>'."<br>";
echo '<tr>';
echo '<td>';
echo '<a href = "'.$path.$file.'"' .'download="'.$file.'">'.$file.'</a>'.'</td>';
echo '<td>'.$row['course'].'</td>';
echo '<td>'.$row['uploader'].'</td>';
echo '<td>'.date('d M Y [H:i:s]', filemtime($path.$file)).'</td>';
echo '<td>'.filesize($path.$file).' Bytes</td>';
echo '</tr>';
}
}
closedir($handle);
}
答案 0 :(得分:1)
尝试一下。
首先,我们创建一个包含所有文件名的数组。然后,我们进行一个查询,并使用WHERE IN子句查找所有结果。我们告诉查询从上传日期开始按降序组织这些结果。
然后,我们使用适当的参数化Mysqli查询从数据库中获取结果。
一旦获得结果,我们便会遍历它们并填充您的表行。
别忘了用正确的列名替换查询中的字段值,否则将无法正常工作。
$path = $dpath . $lpath;
if ($handle = opendir($path)) {
while (false !== ($file = readdir($handle))) {
$dbfname = $path.$file;
if ($file != "." && $file != "..") {
$fileNames[] = $dbfname;
}
}
closedir($handle);
}
if($fileNames){
$clause = implode(',', array_fill(0, count($fileNames), '?'));
$types = str_repeat('s', count($fileNames));
//You will need to change date_field to the column that has the upload dateTime value stored in it.
$sql = "SELECT uploader, course, date_field, filename FROM assignments WHERE filename IN ($clause) ORDER BY date_field DESC";
$stmt = $conn->prepare($sql);
$stmt->bind_param($types, ...$fileNames);
$stmt->execute();
$results = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
}
if($results){
foreach($results as $row){
echo
'<tr>
<td>
<a href="' . $row['filename'] . '"' . 'download="' . basename($row['filename']) . '">' . basename($row['filename']) . '</a>
</td>' .
'<td>' . $row['course'] . '</td>' .
'<td>' . $row['uploader'] . '</td>' .
'<td>' . date('d M Y [H:i:s]', strtotime($row['date_field'])) . '</td>' . //The date_time field is used here too.
'<td>' . filesize($row['filename']) . '</td>' .
'</tr>';
}
}else{
echo
'<tr><td>No results were found</td></tr>';
}