Reputation: 141
I am new to PHP. I have written my code that displays files in a directory, i need the files to be sorted by date modified which is the date uploaded, in a way that shows the latest modified file at the top of the list
this is my code
<?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);
}
Upvotes: 0
Views: 255
Reputation: 3669
Give this a try.
First we make an array with all the file names in it. Then we make one query and use the WHERE IN clause to find all the results. We tell the query to organize those results in a descending order from the date they were uploaded.
We then use a proper parameterized Mysqli query to get the results from the database.
Once we have the results we loop through them and populate your table rows.
Don't forget to replace the field value in the query with the correct column name other wise this will not work correctly.
$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>';
}
Upvotes: 1