Analyze the last 3 records of a table using PHP

Asked

Viewed 59 times

-1

Guys, I need some help.

I have a table where in the price field I need to assess whether the price of the last 3 records were higher than 50. If yes I have to display an alert.

Well catch the last 3 records I could using a select with desc e limit 3. If it were only to display it would be easy the problem is how to evaluate the last 3 records and know if the 3 were greater than 50 or not.

The alert part is also easy, I managing to assess the data I give in echo.

  • You signaled that it is php, but which is the database server? Which database driver are you using? What is the structure of this price list? Detail plus case attributes for a better answer.

  • Database: Mysql. Drive I understand you want to know if I am using Mysqli or PDO, if that is the answer is PDO. The table structure would be id, product name and price. What I need to do is just issue an alert when the last 3 products added in the table cost more than 50 afterwards. For example: pen 40, pencil 60, mouse 70. In this case the alert is not issued because only the last 2 products were greater than 50, so nothing happens. However if pen 60 pencils 70 mouse 80 ai would display an alert Congratulations the 3 last products cost more than 50.

1 answer

0


Create a calculated field in select that signals whether or not the value is below 50:

select preco,
       if preco < 50 then 'S' else 'N' endif as preco_menor
from tabela
order by data desc limit 3

so you will have the three last prices and each of them marked if the value is below or not 50 or other value you wish.

  • Thank you for your reply. From what I understood I would have to create a view with a virtual field that would be the reference, in case you used the S. Thus would be displayed on the screen the last 3 records with the letter s. Now comes the question how would do an if where I would say if the last 3 records = s echo a message?

  • Exact. There are several ways, here is a possible example: $sql = "select price, if preco < 50 then’S' Else 'N' endif as preco_menor from table order by data desc limit 3"; $result = $Conn->query($sql); if ($result->num_rows > 0) { // display each line while($Row = $result->fetch_assoc()) { if ($Row["preco_minor"] = "S") { echo "Price below 50.00". " <br"; } } } Else { echo "Nothing to display"; }

  • Thank you you solved the problem.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.