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
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;

}

 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.