简体   繁体   中英

How to output a value that was recently added into mysql database?

I want to create a table that will output the data from mysql database that was recently added.

Example :

+-----+---------+-----------+---------------+-------------+
| id  | item_id | item_name | borrowed_date | expiry_date |
+-----+---------+-----------+---------------+-------------+
| B01 | N01     | book      | 12/05/2017    | 10/06/2017  |
+-----+---------+-----------+---------------+-------------+

I have tried using ORDER BY but it does not output according to newly added row.

<?php

include"connection.php"; //contain $conn

$query = "SELECT * FROM `database` ORDER BY item_id ASC ;";
$result = mysqli_query($conn,$query);



?>

The output was not according to newly added data

Set your id column to auto increment Give your table another name than Database.

Then use:

SELECT * FROM `yourtable` ORDER BY `id` DESC LIMIT 0,1;

I suggest including one column (like a primary key) that's set to AUTO_INCREMENT . That way you can sort in descending order (DESC) by that ID to get the latest entry.

Something like this:

CREATE TABLE `database` (
    id MEDIUMINT NOT NULL AUTO_INCREMENT,
    [other columns here]
    PRIMARY KEY (id)
);

And then:

SELECT * FROM `database` ORDER BY `id` DESC LIMIT 0,1;

Incidentally, I'm not sure if your table is really named "database". If so, I suggest not using a reserved word . It will work since you're using backticks, but it might be a good idea to change it anyway for various reasons .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM