Jump to content

Return Value from Insert Query


jmfillman

Recommended Posts

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

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;

}

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.