简体   繁体   English

如何使用php获取mysql的最后一个ID

[英]How to get the last ID with mysql using php

I have a form with two stages, the first is to put the information but the second is the UPDATE to add the photo. 我有一个有两个阶段的表单,第一个是放置信息,第二个是UPDATE来添加照片。 So what I want to do is retrieve the last auto incremented ID to update the data, I used LAST_INSERT_ID () 所以我想要做的是检索最后一个自动递增的ID来更新数据,我使用了LAST_INSERT_ID ()

but I realize it is the update everywhere. 但我意识到这是各地的更新。 Do you have a suggestion for me to help me? 你有建议帮我吗? Thank you and sorry sorry for my english. 谢谢,抱歉抱歉我的英文。

You can see here what I did: 你可以在这看到我做了什么:

 $sql = 'UPDATE 'jj_news' SET 
cover_picture="'.$large_image_name.$_SESSION['user_file_ext'].'",
 min_picture="'.$thumb_image_name.$_SESSION['user_file_ext'].'", statut="1",
 edited="'.date('Y-m-d h:i:s').'" WHERE id_news= LAST_INSERT_ID(id_news)';
       mysql_query($sql) or die('Erreur SQL !'.$sql.'<br />'.mysql_error());

You cannot get your id in the "second stage". 你无法在“第二阶段”获得你的身份。 You have to get it immediately after running insert. 运行插入后必须立即获取它。

So, get it in the first stage, store it in a session and then use in the second one. 因此,在第一阶段获取它,将其存储在会话中,然后在第二阶段使用。

血淋淋的地狱,你为什么不把这个该死的id存入一个隐藏的帖子字段并将其传递给表单提交的第二页?

mysql_query("INSERT INTO `xy` (`xy`) VALUES ('$_POST[xy]');");
    $insertId = mysql_insert_id();
    mysql_query("UPDATE xy SET xy='$xy' WHERE id='$insertId'");

only know from the mysql_* function... 只知道mysql_ *函数...

use mysqli or PDO , but if this helps you i´m glad..... 使用mysqli或PDO ,但如果这有助于你我很高兴.....

You can try the following function. 您可以尝试以下功能。

function getLastId($tablename,$id_field){
$id=0;
$sql="select ".$id_field." from ".$tablename." order by ".$id_field." desc limit 1" ;
$res_obj=mysql_query($sql) or die(mysql_error);
if(mysql_num_rows($res_obj)>0){
$result=mysql_fetch_array($res_obj); //we have only on row and column.
$id=$result[$id_field]; //set the last greator Id value;
}
return $id;
}
$newid=getLastId("yourtable","id_field")+1;
//insert your data using $newid instead of autocomplete.
//use $newid during update if update is on new page make a session of $newid. like
$_SESSION['update_id']=$newid;

this function make manual increment of id column, instead of auto increment. 此函数手动增加id列,而不是自动增量。 I think it is ease to control your situation using this function. 我认为使用此功能可以轻松控制您的情况。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM