need a better method for a snippet in php
Say I have a database called Poll
and have these two table structures. poll
table has fields pid
(auto_inc) and title
. choices
table has cid
(auto_inc), pid
, and text
.
How do i add a value to the poll
table and at the same time get the pid
of the most recent entry in the poll
table to be used as the pid
in the choices
table? So far I have this:
<?php
$sql = "INSERT INTO poll (pid, title) VALUES (NULL, 'sometitle')";
if (mysql_query($sql)) {
// get the latest pid
$pid = mysql_result(mysql_query("SELECT pid FROM poll ORDER BY pid DESC LIMIT 1"), 0);
// use the latest pid retrieved to insert to开发者_开发问答 the "choices" table
$sql = "INSERT INTO choices (cid, pid, text) VALUES (NULL, " . $pid . ", 'sometext')";
mysql_query($sql);
}
?>
I just have a feeling that there's a better solution to this.
Thanks!
There are two ways of doing this:
Firstly the PHP function mysql_insert_id(). (See http://www.php.net/mysql_insert_id). This will return the last auto_increment ID inserted.
This doesn't handle large numbers very well, although in practice it ought not to be an issue. The second way (and my preferred way) is to run this query:
Select LAST_INSERT_ID() As insert_id
Make sure to call this before you run any other queries - it must be called directly after the query that does the insert. (See the php.net page above for more info, etc)
The current way you're doing it also suffers from concurrency issues: if somebody else is inserting a poll at the same time, you run the risk of the pids being mixed up.
精彩评论