简体   繁体   中英

How to i take data form last entry stored in my sql database as output in php/html

I have made a form in php and the answer entered is stored in mySQL database. It is stored by incrementing id by 1 in my table On the next page i take the answers from the stored data and display it. But this will show me also the answers entered previously. How can i display only the answers from last id entered? Also i dont want to delete entries from mysql database

On the form page:

session_start(); // At the top of the page


$last_inserted_id = mysqli_insert_id($db); // Just after the mysql insert query

// Save the id in session so that it is available on the next page
$_SESSION['last_inserted_id'] = $last_inserted_id;

On the other page

session_start(); // At the top of the page

if(isset($_SESSION['last_inserted_id'])){

    $the_last_inserted_id = $_SESSION['last_inserted_id'];

    // Query now the database

}

How can i display only the answers from last id entered?

$server = "localhost";
$user = "username";
$password = "password";
$db = "database";

$connection = new mysqli($server, $user, $password, $db);
$sql= SELECT * FROM table ORDER BY id DESC LIMIT 1;
$data = $conn->query($sql);

if ($data->num_rows > 0) {

    while($row = $data->fetch_assoc()) {
        echo "id: " .$row["id"];
    }
}

The "LIMIT 1" means that you only want to get just 1 row from your table and considering ORDER BY DESC it will mean that the last id number you inserted will be selected (because is in descendant order which means that you will get the highest id number)

I hope my example is clear enough.

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