简体   繁体   中英

how to get the associated unique ID of the recently added entry in MYSQL

i need some workaround/solutions for my ajax issue

i have this simple <html>

<textarea class="msg"></textarea>
<button type="button" class="submit">Submit</button>

<div class="messages">
 <?php some php while loop here to display all submitted messages?>
</div>

when i click submit, this ajax gets the value of <textarea> and submits the data into messages.php

$(function() {
    $(document).on('click','.submit', function () {
    var msg = $('.msg').val();

   $.ajax({
     type:"POST",
     url:"messages.php",
     data: "msg=" + msg,
     success: function(html) {
       $(html).prependTo('.messages');
     }
   });
});
});

this is my messages.php

   //insert into database
    $msg= $_POST['msg'];
    $db = dbConnect();
    $insert= "INSERT INTO messages (content)values ('$msg')";
    $db->query($insert);

   //get the recently added message and echo it

    $query = //select the ID of the added message
    $result = $db->($query);
    $row = $result->fetch_assoc());
       echo $row['id'];
       echo $row['content'];

the part where im struggling, is how to query the message being submitted right after it was inserted to the database, so i could echo it in php, and fetch it via ajax.

 success: function(html) {
           $(html).prependTo('.messages');
         }

i know i need some unique identifier of the submitted message, but im not sure how to code it properly.

edit:

ok, the reason i needed to query the added entry, is to get the associated ID of that entry, because i will be using the ID for other functions. all i really need is a reference on my submitted data

$id = $db->insert_id;
$query = "SELECT * FROM messages WHERE id = $id";
$result = $db->query($query);
$row = $result->fetch_assoc();
echo $row['id'];
echo $row['content'];

use last inserted id function it can also help if you are inserting in two different table and inputing same row values

//insert query in this line
$lastid=mysqli_insert_id()//php function
$que = mysqli_query("SELECT * FROM table where id= '$lastid' ");
$r = mysql_fetch_array($que);
echo $r['id'];

hopes this help

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