3

I am creating a calendar in php and grabbing events from a database. We also have to insert events using prepared PDO statements. I can successfully create the new event and insert it into an event table. I also have to link and event with a family member.

$stmt = $handle->prepare("INSERT INTO events(name, description, starthour, meridian, eventdate)
  VALUES(:name, :description, :starthour, :meridian, :eventdate)");
$stmt->execute(array(
    "name" => $name,
    "description" => $description,
    "starthour" => "$starthour",
    "meridian" => "$meridian",
    "eventdate" => "$eventdate"
 ));

$stmt1 = $handle->prepare("INSERT INTO familymemberevents(familymemberID,eventID)
    VALUES(:familymemberID, :eventID)");
$stmt1->execute(array(
    "familymemberID" => $familymemberid,
    "eventID" => 
));

eventID auto-increments. Is there anyway I can get this number from the database? Thanks in advance!

Mihai
  • 26,325
  • 7
  • 66
  • 81
  • http://dev.mysql.com/doc/refman/5.7/en/information-functions.html#function_last-insert-id – Mihai Nov 28 '15 at 19:57
  • PDO has a last insert id function; http://php.net/manual/en/pdo.lastinsertid.php. – chris85 Nov 28 '15 at 19:58
  • $lastId = $stmt1->lastInsertId(); , will return last event id. to know more -http://php.net/manual/en/pdo.lastinsertid.php – jewelhuq Nov 28 '15 at 20:04
  • i would like to suggest one thing use redbeanphp orm for handling data. using direct pdo is really paintful – jewelhuq Nov 28 '15 at 20:05

1 Answers1

3
$stmt = $handle->prepare("INSERT INTO events(name, description, starthour, meridian, eventdate)
    VALUES(:name, :description, :starthour, :meridian, :eventdate)");
$stmt->execute(array(
    "name" => $name,
    "description" => $description,
    "starthour" => "$starthour",
    "meridian" => "$meridian",
    "eventdate" => "$eventdate"
));

$eventID = $handle->lastInsertId();

if($eventID){
    //Event Insert successful, continue with familymemberevent insert
    $stmt1 = $handle->prepare("INSERT INTO familymemberevents(familymemberID,eventID)
        VALUES(:familymemberID, :eventID)");
    $stmt1->execute(array(
        "familymemberID" => $familymemberid,
        "eventID" => $eventID
    ));
}else{
    //Event Insert failed - handle appropriately here
}
micahwittman
  • 12,356
  • 2
  • 32
  • 37