skip to Main Content

I would like to display the last entry made in the database table inside of a text box. Currently all the entries are being displayed in text boxes but i want just one text box that contains the last entry i made into the database table. These is what the output looks like:

output

This is the code that I used to generate the output:

<?php
 $conn = mysqli_connect("localhost", "root", "", "new");
if(!$conn){
die("connection error". mysqli_connect_error());
}
/*else{

    echo"connection successful";
}
*/
$connectDb=mysqli_select_db($conn,"new");
$result = mysqli_query($conn,"select name from new");
while($row = mysqli_fetch_array($result)){
?>
<input type="text" name="name" value="<?php  echo $row['name']; ?>" readonly>
<?php

}

2

Answers


  1. Chosen as BEST ANSWER
    <?php
     $conn = mysqli_connect("localhost", "root", "", "new");
    if(!$conn){
           die("connection error". mysqli_connect_error());
    }
    /*else{
    
        echo"connection successful";
    }
    */
    $connectDb=mysqli_select_db($conn,"new");
    $result = mysqli_query($conn,"SELECT name FROM new ORDER BY ID DESC LIMIT 1");
    while($row = mysqli_fetch_array($result)){
    ?>
    <input type="text" name="name" value="<?php  echo $row['name']; ?>" readonly>
    <?php
    }
    

  2. Database tables have no inherent ordering. How do you define the "last" entry?

    If, for example, you have an ID or date column in your table, you could use that to order your data by time of creation.

    For instance if you have an auto-increment ID column in your table then you could write

    SELECT name FROM new ORDER BY ID DESC LIMIT 1 
    

    to get only the most recently-added record.

    Live demo: https://dbfiddle.uk/jaXDboLq

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search