简体   繁体   English

无法获取最后插入的PHP的ID

[英]Having trouble getting the Id of last inserted PHP

Hello I am trying to use php to insert an object into a MySql table and then get the Id of the newly created object but i can not figure out why it is not working. 您好,我正在尝试使用php将对象插入MySql表中,然后获取新创建的对象的ID,但我不知道为什么它不起作用。 Here is what i have: 这是我所拥有的:

$query = "INSERT INTO `".$Table."` (`ID`) VALUES (NULL);";
$resultset = mysql_query($query, $connection);

$query = "SELECT LAST_INSERT_ID() INTO @".$Table.";";
$resultset = mysql_query($query, $connection);

echo mysql_fetch_assoc($resultset);

The insert works great but I am just getting an empty value where I should be getting the Id. 插入效果很好,但我只是在获取ID的地方得到了一个空值。 Thanks! 谢谢!

New Code: 新代码:

$query = "INSERT INTO `".$Table."` (`ID`) VALUES (NULL); ";
$resultset = mysql_query($query, $connection);
$id = mysql_insert_id();

echo $id;

This SQL query: 这个SQL查询:

 SELECT LAST_INSERT_ID() INTO @Something;

doesn't return a resultset. 不返回结果集。 (It does set the variable.) So, your fetch_assoc statement doesn't get anything back. (它确实设置了变量。)因此,您的fetch_assoc语句什么也得不到。

If you want the id in the resultset do this. 如果您想要结果集中的ID,请执行此操作。

 SELECT LAST_INSERT_ID();

Or, use the mysql_insert_id() function. 或者,使用mysql_insert_id()函数。

Just after executing first query you have to use the function that i tell you:- 在执行第一个查询之后,您必须使用我告诉您的功能:-

$id = mysql_insert_id();

And then change your second query LAST_INSERT_ID() to $id. 然后将第二个查询LAST_INSERT_ID()更改为$ id。

Note:- please take care of double and single quote at the time using $id in second query. 注意:-在第二个查询中使用$ id时,请注意双引号和单引号。

Also mysql_* is officially deprecated now. mysql_ *现在也已正式弃用。 Use mysqli_* or PDO for this purpose. 为此,请使用mysqli_ *或PDO。

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

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