Rockstar Rockstar - 6 months ago 14
MySQL Question

How to get 10 latest records from database

How to display 10 latest jobs from database like this. Please click here to see image

I have written following code so far not sure what to do next.

$query = "SELECT * FROM jobs ORDER BY posting_date DESC LIMIT 10";

$query = mysqli_query($conn, $query);

while ($row = mysqli_fetch_assoc($query) ) {


$job_title = row["job_title"];
$company_name = $row["company_name"];
$department = $row["department"];
$location = $row["location"];
$job_type = $row["job_type"];
$job_description = $row["job_description"];
$posting_date = date('d-m-y');

}


The $row returns all the columns from database. I want only four job title, company name, location and date

Answer

Use column names in select query.

$query = "SELECT job_title,company_name,location,posting_date FROM jobs ORDER BY posting_date DESC LIMIT 10";
$query = mysqli_query($conn, $query);

echo "<table>";
echo "<tr> <th>Job Title</th> <th>Company Name</th> <th>Location</th> <th>Date Posted</th> </tr>";
echo "<tbody>";  
while($row = mysqli_fetch_assoc($query) ) {
  $job_title = $row["job_title"];
  $company_name = $row["company_name"];
  $department = $row["department"];
  $location = $row["location"];   
  $posting_date = date('d-m-y', strtotime($row['posting_date']));

  echo "<tr>";
  echo "<td>".$job_title."</td>";
  echo "<td>".$company_name."</td>";
  echo "<td>".$location."</td>";
  echo "<td>".$posting_date."</td>";
  echo "<tr>";
}
echo "</tbody>";
echo "</table>";
Comments