正在从已提交数据的数据库中获取id

Fetching id from database of submitted data

本文关键字:数据库 获取 id 数据 提交      更新时间:2023-09-26

所以我正在向数据库提交数据。发送的每个数据都包含一个自动递增的id。使用ajax或PHP(我对此非常陌生,为了学习,我确信这是ajax和一些PHP),我需要获取提交的数据的id。

这个想法是,在表单提交后,用户可以获得返回到提交页面的链接。示例:

报价已提交![link]单击可转到链接或返回。

链接将如下所示:http://example.com/quote-192我几乎已经设置了所有其他内容,我只是不知道如何获取id并将其添加到链接中。

以下是处理表单的PHP:

require('inc/connect.php');

    $quote = $_POST['quote'];
    $quotes = mysql_real_escape_string($quote);
    //echo $quotes . "Added to database";
    mysql_query("INSERT INTO entries (quote) VALUES('$quotes')")
    or die(mysql_error());

哦,数据是用ajax发送的:

 $(document).delegate("'#submit-quote'", "submit", function(){
        var quoteVal = $(this).find('[name="quote"]').val();
        $.post("add.php", $(this).serialize(), function() {
            var like = $('.quote-wrap span iframe');
            $('.inner').prepend('<div class="quote-wrap group">' + like + '<div class="quote"><p>' + quoteVal+ '</p></div></div>');
            // console.log("success");
        });
        return false;
    });

那么,在提交表单后,我如何获得每个报价的id并将其添加到页面中呢?

在php:中

echo mysql_insert_id($result)

然后在您的jquery ajax中:

$.ajax({
type:'post',
url:'url.php',
data:querystring,
success:function(data){
  var id = parseInt(data);
}
]);

这将以整数值的形式返回插入的ID,您可以在JavaScript

中使用它

让PHP打印ID作为对请求的响应:

mysql_query("INSERT INTO entries (quote) VALUES('$quotes')")
    or die(mysql_error());
// Print the id of last insert as a response
echo mysql_insert_id();

jQuery,测试代码,以提醒PHP将什么作为测试进行响应

// add data as a param to the function to have access to the PHP response    
$.post("add.php", $(this).serialize(), function(data) {
  alert(data);
});

使用这个php函数。插入后可以调用。

int mysql_insert_id ([ resource $Verbindungs-Kennung ] )

mysql_insert_id