Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I select the most recent entry in mysql?

Tags:

php

mysql

i want to select the most recent entry from a table and see if that entry is exactly the same as the one the user is trying to enter. How do I do a query to "select * from the most recent entry of 'posting'"?

    $query="Select * FROM 
        //confused here 
 (SELECT * FROM posting ORDER BY date_added DESC)
 WHERE user_id='{$_SESSION['user_id']}'
 AND title='$title'
 AND price='$price'
 AND city='$city'
 AND state='$state'
 AND detail='$detail'
 ";

 $data = mysqli_query($dbc, $query);
 $row = mysqli_fetch_array($data);
 if(mysqli_num_rows($data)>0)
 {
  echo "You already posted this ad. Most likely caused by refreshing too many times.";
  echo "<br>";
  $linkposting_id=$row['posting_id'];
  echo "See the <a href='ad.php?posting_id=$linkposting_id'>Ad</a>";
 }
 else
 {
        ...insert into the dbc
        }

//would this query work? or how do i use it to select the last ID in the table 'posting'?
    $query="SELECT LAST_INSERT_ID(posting)
     WHERE user_id='{$_SESSION['user_id']}'
     AND title='$title'
     AND price='$price'
     AND city='$city'
     AND state='$state'
     AND detail='$detail'
     ";
like image 840
ggfan Avatar asked Apr 17 '10 19:04

ggfan


People also ask

How do I find the latest entry in SQL table?

We can use the command FIRST() to extract the first entry of a particular column and LAST() to extract the last entry of a particular column in a Table.

How do I select recent data in SQL?

The LAST() function in Structured Query Language shows the last value from the specified column of the table.

How do I select recently updated table records?

IDENT_CURRENT() function accepts the table name(AuthorsNew) and returns the last identity value generated for AuthorsNew table . By using this facility we can find the last inserted record.

How do I get latest 10 records in MySQL?

SELECT * FROM ( SELECT * FROM yourTableName ORDER BY id DESC LIMIT 10 )Var1 ORDER BY id ASC; Let us now implement the above query. mysql> SELECT * FROM ( -> SELECT * FROM Last10RecordsDemo ORDER BY id DESC LIMIT 10 -> )Var1 -> -> ORDER BY id ASC; The following is the output that displays the last 10 records.


1 Answers

The orderby piece needs to come at the end of your query. So the query you're asking for is something like this:

select * from posting where .... order by date_added desc limit 1;

Single-use form tokens can help prevent duplicate submissions, too.

like image 138
grossvogel Avatar answered Oct 04 '22 09:10

grossvogel