简体   繁体   中英

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. It's auto increment value so I added NULL.

how can I use this coin_ID in this same page, after I ran some checking with PHP?

thanks

PHP中的mysql_insert_id或mysql中的LAST_INSERT_ID

参见mysql_insert_id

It depends on which database driver you are using with PHP. If you are using the standard mysql functions you can use the mysql_insert_id function:

$coin_id = mysql_insert_id()

If you are using PHP's PDO then you can use the lastInsertId () method:

$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. MySQL doesn't support it however.

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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