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 to generate a PDO query using named placeholder for the below statement.
INSERT INTO propAmenities (amenity_id, property_id) VALUES (1, 1), (2, 1), (3, 1)
i tried using the following syntax but i am not sure if this will work.
$sth->$this->dbh->prepare('INSERT INTO
propAmenities
(amenity_id, property_id)
VALUES
(:amenity_id, :property_id),
(:amenity_id, :property_id),
(:amenity_id, :property_id)');
and for the above query i am not sure how do i use PDO's bindParam() ? how do i handle this situation Using PDO? am i using the wrong PDO's Placeholders?
A PDO database connection requires you to create a new PDO object with a Data Source Name (DSN), Username, and Password. The DSN defines the type of database, the name of the database, and any other information related to the database if required. These are the variables and values we stated inside the dbconfig.
To select data from a table using PDO, you can use: The query() method of a PDO object. Or a prepared statement.
You can give the placeholders whatever names you want so something like this for your SQL:
INSERT INTO propAmenities
(amenity_id, property_id)
VALUES
(:amenity_id1, :property_id1),
(:amenity_id2, :property_id2),
(:amenity_id3, :property_id3)
And then:
$stmt->bindParam(':amenity_id1', 1);
$stmt->bindParam(':property_id1', 1);
$stmt->bindParam(':amenity_id2', 2);
$stmt->bindParam(':property_id2', 1);
$stmt->bindParam(':amenity_id3', 3);
$stmt->bindParam(':property_id3', 1);
Or, of course, build the appropriate array for execute
. In this case, non-named placeholders might be easier to work with though:
INSERT INTO propAmenities
(amenity_id, property_id)
VALUES
(?, ?),
(?, ?),
(?, ?)
And then you can loop through your values and call execute
with the appropriate array:
$stmt->execute(array(1, 1, 2, 1, 3, 1));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With