Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do i Insert Multiple records in one database trip using PDO?

Tags:

php

mysql

pdo

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?

like image 575
Ibrahim Azhar Armar Avatar asked Jun 04 '11 08:06

Ibrahim Azhar Armar


People also ask

How does PDO connect to database?

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.

How do I select a database in PDO?

To select data from a table using PDO, you can use: The query() method of a PDO object. Or a prepared statement.


1 Answers

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));
like image 88
mu is too short Avatar answered Sep 17 '22 14:09

mu is too short