简体   繁体   English

如何在同一SQL查询中插入和选择数据?

[英]How to insert and select data in the same SQL query?

I used query like this 我这样查询

INSERT INTO coins VALUES (NULL, '$user_ID', '$title', NOW())

now later in this same script page, I need to use value coin_ID that I just inserted in the query above. 现在稍后在同一脚本页面中,我需要使用刚刚在上面的查询中插入的值coin_ID。 It's auto increment value so I added NULL. 它是自动增量值,所以我添加了NULL。

how can I use this coin_ID in this same page, after I ran some checking with PHP? 使用PHP运行检查后,如何在同一页面中使用此coin_ID?

thanks 谢谢

PHP中的mysql_insert_id或mysql中的LAST_INSERT_ID

参见mysql_insert_id

It depends on which database driver you are using with PHP. 这取决于PHP使用的数据库驱动程序。 If you are using the standard mysql functions you can use the mysql_insert_id function: 如果使用标准的mysql函数,则可以使用mysql_insert_id函数:

$coin_id = mysql_insert_id()

If you are using PHP's PDO then you can use the lastInsertId () method: 如果您使用的是PHP的PDO,则可以使用lastInsertId ()方法:

$coin_id = $DB->lastInsertId()

If you are using a database that supports the RETURNS sql keyword (such as postgres) then you can do it in one query. 如果您使用的数据库支持RETURNS sql关键字(例如postgres),则可以在一个查询中进行操作。 MySQL doesn't support it however. MySQL不支持它。

INSERT INTO coins VALUES (NULL, '$user_ID', '$title', NOW()) RETURNING coin_id;

If you edit your post to include the method of database interaction that you are using, we can provide a more specific answer. 如果您编辑帖子以包括您正在使用的数据库交互方法,我们可以提供更具体的答案。

使用mysql_insert_id检索最后插入的ID。

$coin_ID = mysql_insert_id();

尝试通过PHP mysql_insert_id函数使用LAST_INSERT_ID()

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

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