user3527379
user3527379

Reputation:

How To Get The Last Entry From MYSQL Database?

I am trying to get the last id which I entered to my database. Here is the code I use:

$test_query = "SELECT * FROM table ORDER BY id DESC LIMIT 1";

    if ( mysql_query($test_query) ) {
        echo 'OK!';
        $results = mysql_fetch_array($test_query);
        echo $results['id'];    
        print_r ($results);
    }

The only output I have is the 'OK!'.

What do i do wrong?

Upvotes: 2

Views: 186

Answers (2)

smoore4
smoore4

Reputation: 4866

You can use this if you have an auto-increment field in the table:

SELECT LAST_INSERT_ID();

Upvotes: 1

Halcyon
Halcyon

Reputation: 57709

You need to use the output of mysql_query in mysql_fetch_array.

$res = mysql_query($test_query);
if ($res === false) {
    throw new Exception("query failed");
}
$row = mysql_fetch_array($res);
echo $row["id"];

Keep in mind that this reads only one row. If you want more use the while loop construction you can find here: http://php.net/mysql_fetch_array


If you just did an INSERT query use mysql_insert_id() to fetch the id. This is a feature of MySQL. This works in conjunction with the AUTO_INCREMENT option.


Also, if this is a new site you're building use mysqli_* functions instead of mysql_*. The latter is deprecated.

Upvotes: 3

Related Questions