I am trying to get the last inserted id in the database and use that to insert another record(s), in this case, associated images with a particular record. Note: I am using MVC and this is in the model. These 2 operations should happen straight after each other i.e.: the user does't see that there are 2 different inserts happening at the same time.
This is the initial insert:
public function addAccom($data)
{
$this->db->query("INSERT INTO `accommodation` (`name`, `description`, `category`, `slug`) VALUES (:name, :description, :category, :slug)");
$this->db->bind(":name", $data['name']);
$this->db->bind(":description", $data['description']);
$this->db->bind(":category", $data['category']);
$this->db->bind(":slug", $data['slug']);
if($this->db->execute()){
$id = $this->db->lastInsertId();
return true;
} else {
return false;
}
}
I don't know if this line is correct in the above:
$id = $this->db->lastInsertId();
After this insert, I need to insert more records into another table using that id.
Should I try run another db query in the same query as this or create another query?
This is the second query I had:
public function addAccomPic($data)
{
$this->db->query("INSERT INTO `accom_pics` (`accom_id`, `pic_name`) VALUES (:accom_id, :pic_name)");
$this->db->bind(":accom_id", $data['accom_id']);
$this->db->bind(":pic_name", $data['pic_name']);
if($this->db->execute()) {
return true;
} else {
return false;
}
}
Database:
private $host = DB_HOST;
private $user = DB_USER;
private $pass = DB_PASS;
private $dbname = DB_NAME;
private $dbh; // Is this the same as $link ?
private $stmt;
private $error;
public function __construct() {
$dsn = "mysql:host=$this->host;dbname=$this->dbname";
$options = array(
PDO::ATTR_PERSISTENT => true,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
);
try {
$this->dbh = new PDO($dsn, $this->user, $this->pass, $options);
} catch(PDOexception $e) {
$this->error = $e->getMessage();
echo $this->error;
}
}