-1

I'm trying to get results from the database and I would like to show the info starting from the last ID, not the first one, is this possible?

$query = $db->prepare("SELECT * FROM grafica WHERE ID = :id");
$query->bindParam(':id', $id);
$query->execute();
$result = $query->fetchAll();

foreach ($result as $row) {


}
Richard II
  • 853
  • 9
  • 31

1 Answers1

0

Presumably, ID is unique, so your question does not currently make sense in context of the query posted: the query will return exactly 1 or 0 rows, depending on if a row with ID = :id exists. If you want to view a list of rows, perhaps in ascending or descending order of ID, do not restrict the results with ID = :id, and use the ORDER BY clause:

$query = $db->prepare("SELECT * FROM grafica ORDER BY ASC");
# $query = $db->prepare("SELECT * FROM grafica ORDER BY DESC");  # for descending order
$query->execute();

Note that there is now no need for the bindParam call.

hunteke
  • 3,648
  • 1
  • 7
  • 17
  • I have replaced ID = :id for only Id desc. Is this secure? Thanks – user3430043 May 21 '18 at 13:29
  • 1
    In this limited context, yes. The SQL query would not be created with any user-sent input and will be exactly as you, the programmer, intended. This SQL, without string interpolation, has no chance for a user to change its intent. As an aside: kudos for using prepared statements already. For a _little_ more on the security aspect, [peruse this Q&A](https://stackoverflow.com/questions/47272504/getting-rid-of-sql-injection-without-using-prepared-statement), specifically the edit. – hunteke May 21 '18 at 14:00