2016-03-03 62 views
0

我與特定的問題鬥爭,我需要插入數據到不同結構的多個表。插入到所有列而不是指定每個[MYSQL或PSQL]

大氣壓我有我的劇本是這樣的:

public function insertToPsql($manufacturer_code, $main_type, $subtype_code, $manufacturer, $model, $submodel) 
    { 
     try { 
      $con = new PDO(PSQL_DB_HOST, PSQL_DB_HOST, PSQL_DB_HOST); 
      $con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 
      $sql = "INSERT INTO car_type(manufacturer_code, main_type, subtype_code, manufacturer, model, submodel) VALUES(:manufacturer_code, :main_type, :subtype_code, :manufacturer, :model, :submodel)"; 
      $stmt = $con->prepare($sql); 
      $stmt->bindValue('manufacturer_code', $manufacturer_code, PDO::PARAM_STR); 
      $stmt->bindValue('main_type', $main_type, PDO::PARAM_STR); 
      $stmt->bindValue('subtype_code', $subtype_code, PDO::PARAM_STR); 
      $stmt->bindValue('manufacturer', $manufacturer, PDO::PARAM_STR); 
      $stmt->bindValue('model', $model, PDO::PARAM_STR); 
      $stmt->bindValue('submodel', $submodel, PDO::PARAM_STR); 
      $stmt->execute(); 
     } 
     catch(PDOException $e) { 
      echo $e->getMessage(); 
      exit; 
     } 
    } 

的事情是,這是不是最好的辦法,如果我需要隨時修改它爲每個表(很多我的表有大約40列)。

好東西是,我總是插入所有的人。有什麼辦法如何插入到所有列和不指定數據,但只是給它一個數組或對象的所有數據?

喜歡的東西:

$sql = "INSERT INTO car_type VALUES(:$data)"; 
+0

您在使用MySQL或PostgreSQL?你有兩個標籤。 – Barmar

回答

1

如果你有一個數組,其元素是相同的順序在表中的列,你可以這樣做:

$values = array($manufacturer_code, $main_type, $subtype_code, $manufacturer, $model, $submodel); 
$placeholders = implode(',', array_fill(0, count($values), '?')); 
$sql = "INSERT INTO car_type VALUES ($placeholders)"; 
$stmt = $con->prepare($sql); 
$stmt->execute($values); 
相關問題