【问题标题】:Fetching id from database of submitted data从提交数据的数据库中获取 id
【发布时间】:2012-02-10 06:41:55
【问题描述】:

所以我正在向数据库提交数据。发送的每个数据都包含一个自动递增的 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 并在提交表单后将其添加到页面中?

【问题讨论】:

    标签: php javascript jquery ajax database


    【解决方案1】:

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

    int mysql_insert_id ([ resource $Verbindungs-Kennung ] )
    

    mysql_insert_id

    【讨论】:

      【解决方案2】:

      让 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);
      });
      

      【讨论】:

      • 编辑:当我发出警报时,我使用 parseInt 得到 NaN。如果我不使用 parseInt,那么警报会显示一堆乱七八糟的 HTML ..... 显示 PHP 给出错误。
      【解决方案3】:

      在你的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 中使用该值

      【讨论】:

      • 我真的是 ajax 新手。如何在我正在使用的代码中工作?
      • 我写它的方式是做 jQuery 的长格式方式。您可以将您的序列化语句添加到我有“查询字符串”的位置,并将您的回调添加到成功函数所在的位置。 api.jquery.com/jQuery.ajax 通读一遍,看看是否更有意义。
      猜你喜欢
      • 2021-02-03
      • 1970-01-01
      • 2020-10-29
      • 2012-02-10
      • 1970-01-01
      • 2015-04-23
      • 2016-08-20
      • 2017-12-28
      • 2017-09-12
      相关资源
      最近更新 更多