选择表中所选行的最后插入ID

时间:2013-12-17 00:08:03

标签: php mysql

有没有办法让我从选定的行中选择最后插入的id。 (不是表中的所有行)下面是我写的代码。我想选择一个具有最高值属性的一个。这也是所选集合的最后插入ID。

$get_payment_details = 'SELECT * FROM payment WHERE m_id="' . $mselcted_memberI . '" AND app_id= "' . $aprvd_appid . '"';

$get_payment = mysql_query($get_payment_details);
$get_pay_result = mysql_fetch_assoc($get_payment);
$get_pay_count = mysql_num_rows($get_payment);

if ($get_pay_count < 1) {
    $query1 = "INSERT INTO payment(date,m_id,app_id,week,capital_topay,interest_to_pay,received,advanced,remain_capital,remain_interest)
               VALUES('$date1',"."'".$mselcted_memberI."',"."'".$aprvd_appid."',"."'".$week1."',"."'".$aprvd_amount."',"."'".$ttl_interest."',"."'".$received1."',"."'".$advanced1."',"."'".$aprvd_amount."',"."'".$ttl_interest."')";
    $login_set = mysql_query($query1,$connection);
    confirm_query($login_set);
    echo $week1;
} else if ($get_pay_count >0){

}

3 个答案:

答案 0 :(得分:1)

如果您使用的是PHP 5.5之前的版本,则可以使用mysql_insert_id()来检索上次插入的ID。来自文档:

<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
    die('Could not connect: ' . mysql_error());
}
mysql_select_db('mydb');

mysql_query("INSERT INTO mytable (product) values ('kossu')");
printf("Last inserted record has id %d\n", mysql_insert_id());
?>

但请注意,自PHP 5.5.0起,此函数已弃用。规范推荐的解决方案如下:

答案 1 :(得分:0)

我不确定你到底是什么意思,但要从sql获取最后一个自动生成的id,请使用

$theID = mysqli_insert_id();

以下是更多信息:

http://php.net/manual/en/mysqli.insert-id.php

答案 2 :(得分:0)

你需要:

SELECT id FROM payment WHERE yourConditions ORDER BY week DESC LIMIT 0,1;