0

Possible Duplicate:
PDO Prepared Inserts multiple rows in single query

Hey all. I'm writing a script with an array of names each of which will be added to a new row in a MySQL database with other columns added in as well. The statement I'm trying to achieve with PDO resembles the following code:

$sql = 'INSERT INTO table 
(name, car, gender) 
VALUES 
("Name", "Car", "Gender"),
("Name2", "Car2", "Gender2"),
("Name3", "Car3", "Gender3"),
("Name4", "Car4", "Gender4"),
("Name5", "Car5", "Gender5")';

Is there a way to achieve this with a PDO Statement? I guess I could do it like the following, but I don't feel this is the most efficient way to achieve this.

$namesarray = array("Name1", "Name2", "Name3", "Name4", "Name5");

foreach($namesarray as $name)
{
  try 
  {
   $conn = parent::connect();
   $st = $conn->prepare($sql);
   $st->bindValue(":name", $this->data['name'], PDO::PARAM_STR);      
   $st->bindValue(":car", $this->data['car'], PDO::PARAM_STR);       
   $st->bindValue(":gender", $this->data['gender'], PDO::PARAM_STR);      
   $st->execute();  
   parent::disconnect($conn);
   return true;
  }
  catch (PDOException $e)
  {
   parent::disconnect($conn);
   die("Query failed: " . $e->getMessage());
  }
}
Community
  • 1
  • 1
Tableking
  • 276
  • 3
  • 11
  • if $namesarray is empty, how could your foreach statement be useful? – greg0ire Jan 30 '11 at 15:44
  • Is there a reason you're disconnecting from your database after each iteration? – Tim Cooper Jan 30 '11 at 15:45
  • @greg0ire The names array is not empty, I just have that there as an example of the code I'm using to let you know that's an array. I'll populate it to avoid confusion. – Tableking Jan 30 '11 at 15:52

0 Answers0