jmfillman Posted February 25, 2008 Share Posted February 25, 2008 Take this code: public function addApp($id, $date, $month, $year, $day) { if ($id==0) { $query = "INSERT INTO app (date, month, year, day) VALUES ($date, '$month', '$year', '$day')"; $result = mysql_query($query); $msg=$this->err_prefix."INSERT query error: ".$this->mysql->error; throw new Exception($msg); } This query obviously inserts a record into the app table. The $id field is an auto_increment field on the database, but I need to return the id that the database creates. I cannot simply take the last id in the database, since multiple users are inserting records simultaneously. So how can I find and return this information? Link to comment https://forums.phpfreaks.com/topic/92965-return-value-from-insert-query/ Share on other sites More sharing options...
revraz Posted February 25, 2008 Share Posted February 25, 2008 mysql_insert_id http://dev.mysql.com/doc/refman/5.0/en/getting-unique-id.html Link to comment https://forums.phpfreaks.com/topic/92965-return-value-from-insert-query/#findComment-476301 Share on other sites More sharing options...
jmfillman Posted February 26, 2008 Author Share Posted February 26, 2008 From the documentation, it looks like last_insert_id(), is the better option in that it's connection specific. I'm not certain of the usage or syntax for this, but I've found other examples that seem to do the same thing I have here. However, this is returning a null value. I am not terribly familiar with PHP syntax either (generally use ActionScript). So, what am I doing wrong here? public function addApp($id, $date, $month, $year, $day) { if ($id==0) { $query = "INSERT INTO apps (date, month, year, day) VALUES ('$date', '$month', '$year', '$day')"; $result = mysql_query($query); $msg=$this->err_prefix."INSERT query error: ".$this->mysql->error; throw new Exception($msg); $idQuery = "SELECT LAST_INSERT_ID()"; $idResult = mysql_query($idQuery); $msg=$this->err_prefix."ID query error: ".$this->mysql->error; throw new Exception($msg); } else { $query = "UPDATE appointments SET date='$date', month='$month', year='$year', day='$day' WHERE id='$id'"; $result = mysql_query($query); $msg=$this->err_prefix."UPDATE query error: ".$this->mysql->error; throw new Exception($msg); } return $idResult; } Link to comment https://forums.phpfreaks.com/topic/92965-return-value-from-insert-query/#findComment-477424 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.