2012-01-14 120 views
0

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

想法是,在表单提交后,用户将链接返回到提交的页面。例如:

报价已提交! [链接]点击进入链接或返回。

的链接将是这样的: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为每一个报价,并添加它提交表单后的页面?

回答

1

在你身边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

+0

我对阿贾克斯真的很陌生。我如何在我使用的代码中工作? – nowayyy 2012-01-15 00:38:05

+0

我写这个的方式是做jQuery的一种很长的形式。你可以将你的序列化语句添加到我有'查询字符串'的位置,并将你的回调添加到成功函数所在的位置。 http://api.jquery.com/jQuery.ajax/通读这一点,看看它是否更有意义。 – Ethan 2012-01-15 06:07:16

0

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

int mysql_insert_id ([ resource $Verbindungs-Kennung ]) 

mysql_insert_id

0

有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); 
}); 
+0

当我提醒,我得到NaN的 – nowayyy 2012-01-15 00:41:33

+0

编辑工作:当我警报,我得到NaN parseInt。如果我不使用parseInt,那么警报会显示一堆乱七八糟的HTML .....显示PHP给出错误。 – nowayyy 2012-01-15 00:47:25