Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select the most recent 5 rows based on date

Tags:

php

mysql

pdo

I haven't touched PHP in a while and trying to select the 5 most recent entries in my database and print them to screen.

I see mysql command isn't recommended anymore and to use PDO->mysql instead.

My query is something like this:

SELECT id,title,date,author FROM table ORDER BY date DESC LIMIT 5;

I'm assuming I would have to put the values into an array and create a loop and output the results.

<?php
$db = new PDO('mysql:dbhost='.$dbhost.';dbname='.$dbname, $user, $pass);

while () {
  print($title[$i], $date[$i], $author[$i]);
  $i++
}

$db = null;

?>

I'm stuck filling in the gaps with the above code.

Update: The $db = new PDO.... line is reporting an error message:

PHP Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[HY000] Can't connect to local MySQL server through socket... in /var/...

PDO is confirmed to be installed and enabled. My other web apps on the server can connect to the same remote mysql server fine.

like image 933
user1052448 Avatar asked Oct 26 '15 01:10

user1052448


People also ask

How do I get last 5 rows in SQL?

METHOD 1 : Using LIMIT clause in descending order As we know that LIMIT clause gives the no. of specified rows from specifies row. We will retrieve last 5 rows in descending order using LIMIT and ORDER BY clauses and finally make the resultant rows ascending.

How do I select the rows with the most recent date in SQL?

Here is the syntax that we can use to get the latest date records in SQL Server. Select column_name, .. From table_name Order By date_column Desc; Now, let's use the given syntax to select the last 10 records from our sample table.

How do I select the last 3 rows in SQL?

Try only this:- SELECT * FROM reset ORDER BY ASC LIMIT (FOUND_ROWS() - 3), 3 and check if it is giving the last 3 rows from your table in ascending order!!!

How do I get the latest record using timestamp in SQL?

To get the last updated record in SQL Server: We can write trigger (which automatically fires) i.e. whenever there is a change (update) that occurs on a row, the “lastupdatedby” column value should get updated by the current timestamp.


1 Answers

<?php
$host = 'localhost'; $db = 'db-name'; $user = 'db-user'; $pw = 'db-password';
$conn = new PDO('mysql:host='.$host.';dbname='.$db.';charset=utf8', $user, $pw);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
?>

<?php
$sql = "SELECT id,title,date,author FROM table ORDER BY date DESC LIMIT 5";
$query = $conn->prepare($sql);
$query->execute();
$row = $query->fetch(PDO::FETCH_ASSOC);
$totalRows = $query->rowCount();
?>

<?php do {
// print your results here ex: next line
echo 'Title: '.$row['title'].' Date: '.$row['date'].' Author: '.$row['author'].'<br>'; 
} while ($row = $query->fetch(PDO::FETCH_ASSOC)); ?>

Don't forget to close and release resources

<?php $query->closeCursor(); ?>

EDIT

I recommend not echoing error messages once you have confirmed your code functions as expected; however if you want to simply use plain text you can do this...

You can add this to your connection block...

if ($conn->connect_error) {
    die("Database Connection Failed");
    exit;
}

You can also change your query block...

try {
    $sql = "SELECT id,title,date,author FROM table ORDER BY date DESC LIMIT 5";
    $query = $conn->prepare($sql);
    $query->execute();
    $row = $query->fetch(PDO::FETCH_ASSOC);
    $totalRows = $query->rowCount();
} catch (PDOException $e) {
    die("Could not get the data you requested");
    exit;
}

Again, it is recommended that errors not be echoed. Use error checking only for debugging.

like image 50
Kuya Avatar answered Oct 27 '22 08:10

Kuya