我有一个表学生,表格结构如下
student_id | name | class|
-------------------------
2-12-2013 | test | 3 |
-------------------------
2-13-2013 |test2 | 5 |
-------------------------
在此表中我想添加新记录,其student_id变为 2-14-2013 。为此,我想获得最后插入的student_id。我如何通过 MySQL查询获得它。 alredy使用mysql_insert_id()
但它不起作用,如何解决这个问题?
答案 0 :(得分:1)
定义您的学生表如下: -
student_id | add_date | name | class|
--------------------------------------
1 | 2013-12-2 | test | 3 |
--------------------------------------
2 | 2013-13-2 |test2 | 5 |
--------------------------------------
student_id将是int auto递增主键
然后执行如下的查询以获取最后插入的ID: -
select student_id from student order by student_id desc limit 1;
答案 1 :(得分:1)
您好必须将主键设置为整数自动增量表,然后才能使用此最后插入的ID
$con = mysql_connect("localhost", "root", "", "chirag2");
$sql = "INSERT INTO test_student ( student_id,name,class)values('3-12-2013','test1','3' )";
$res = mysql_query($con, $sql);
echo mysql_insert_id($con);
die;
注意:您需要在更改表之前截断表并为其设置新的主键,因此请在此之前进行备份