【问题标题】:return the last id when insert the data in mysql using PHP使用PHP在mysql中插入数据时返回最后一个id
【发布时间】:2014-01-13 04:45:48
【问题描述】:

我尝试在将数据插入 mysql 后获取最后一个 id。我已经尝试使用 mysql_insert_id() 但它似乎不起作用。

以下是 PHP 代码:

 function addPhoneContact($customername ,$address ,$email ,$comment,$remarks){

        $connection = MySQLConnection();
        $conf = new BBSupervisorConf();
        $log = new KLogger($conf->get_BBLogPath().$conf->get_BBDateLogFormat(),  $conf->get_BBLogPriority() );

        $query="INSERT INTO bb_customer 
                (customername,address ,email ,comment,remarks) 
                VALUES
               ('".$customername."','".$address."','".$email."','".$comment."','".$remarks."');";


            $customerid = mysql_insert_id();
        try {
        $log->LogDebug("Query[".$query."]");
        if (!mysql_query($query)){
            die (mysql_error());      
        }else{
    }
      }catch(Exception $e){
          $log->LogError($e->getMessage());
      }

        closeDB($connection);
        return $customerid;
    }

感谢您的帮助。

【问题讨论】:

  • 您的 $query 执行是否正确?还有为什么您的 $query 中有一个额外的分号?

标签: php mysql function mysqli


【解决方案1】:

放这条线

$customerid = mysql_insert_id();

在你执行查询之后

mysql_query($query)

如果不执行mysql查询,它不会知道id。

强烈考虑不要使用 mysql_* 函数。

Why shouldn't I use mysql_* functions in PHP?

【讨论】:

  • -1 用于支持使用已弃用的mysql_ 函数而不建议使用mysqliPDO
  • @Nikola 我很欣赏你的想法。您也可以编辑答案。是什么阻止你这样做?
  • @chanchal118,没有什么能阻止我,但我不明白为什么我要写这个信息,当它是你的答案时。我投了反对票,因为我相信这个问题没有以最好的方式回答(实际上比中性更糟糕),因此给你一个评论,你可以如何改进它。如果你这样做,我可以很容易地改变我的投票。我相信投票否决是正确的,因为不应再使用 mysql_ 函数,即使 mysql_insert_id() 会完成这项工作,您也应该提出更好的方法 [替代]
  • 在 SO 我们不参加考试。这是一个社区。我们应该始终以最好的方式改进问题或答案。询问Why you have not done that? 不是最好的方法。
  • @chanchal118 提出这样的问题正是 cmets 的用途,编辑不应改变答案的预期含义。
【解决方案2】:
 function addPhoneContact($customername ,$address ,$email ,$comment,$remarks){

    $connection = MySQLConnection();
    $conf = new BBSupervisorConf();
    $log = new KLogger($conf->get_BBLogPath().$conf->get_BBDateLogFormat(),  $conf->get_BBLogPriority() );

    $query="INSERT INTO bb_customer 
            (customername,address ,email ,comment,remarks) 
            VALUES
           ('".$customername."','".$address."','".$email."','".$comment."','".$remarks."');";


        $customerid = mysql_insert_id(); //comment this out
    try {
    $log->LogDebug("Query[".$query."]");
    if (!mysql_query($query)){
        die (mysql_error());      
    }else{
}
  }catch(Exception $e){
      $log->LogError($e->getMessage());
  }
    $customerid = mysql_insert_id(); //add here
    closeDB($connection);
    return $customerid;
}

【讨论】:

    猜你喜欢
    • 2014-06-19
    • 2012-04-05
    • 2013-09-13
    • 1970-01-01
    • 2014-12-05
    • 2011-11-06
    • 2014-09-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多