i have a table called propAmenities which holds two column amenity_id and property_id basically the table holds the foreign keys.
now i have two insert data into this table, and while inserting data property_id column will have the same value for all rows that are to be inserted while amentiy_id value will vary, now for example the values may look like
INSERT INTO propAmenities(amenity_id, property_id) VALUES(1,1);
INSERT INTO propAmenities(amenity_id, property_id) VALUES(2,1);
INSERT INTO propAmenities(amenity_id, property_id) VALUES(3,1);
INSERT INTO propAmenities(amenity_id, property_id) VALUES(4,1);
INSERT INTO propAmenities(amenity_id, property_id) VALUES(5,1);
and the current code to insert the data i am using is:
public function savePropAmenities($amenityIds = array()) {
if($this->validateRequired(array('propertyId'))) {
foreach($amenityIds as $amenityId) {
$sth = $this->dbh->prepare('INSERT INTO
propAmenities
(amenity_id, property_id)
VALUES
(:amenityId, :propertyId)');
$sth->bindParam(':amenityId', $amenityId);
$sth->bindParam(':propertyId', $this->data['propertyId']);
$sth->execute();
}
}
}
the above code will run a loop and will make a frequent trip to database to insert the records. is there anyway i could cut of the trip and minimize it to one?
You can do a multi value insert (for MySQL atleast)
Also you can set a default value for the field on the database.
Then you could do this