2011-06-13 80 views
1

我想知道是否有辦法做到以下不會導致我錯誤。有人能夠解釋爲什麼以下是不可能的,以及我怎麼能把它關掉?PHP和PDO問題

下面是函數:

public function getTaxClass() 
{ 
    $arg = func_get_args(); 
    $pid = array_shift($arg); 
    $imp = implode(',',$arg); 

    $stmt = _DB::init()->prepare("SELECT $imp 
           FROM tax_class a 
           INNER JOIN products_to_tax_class pa ON a.tid = pa.tid 
           WHERE pa.pid = ?" 
          ); 
    if($stmt->execute(array($pid))) 
    return $stmt->fetch(PDO::FETCH_ASSOC); 

} 

我無法插入變量到準備好的聲明?我試圖建立其添加到準備前的字符串,但是我仍然得到以下警告:

Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[23000]: Integrity constraint violation: 1052 Column 'tid' in field list is ambiguous' in /class.php:89 Stack trace: #0 /class.php(89): PDOStatement->execute() #1 /class.php(98): _Class->getTaxClass(1, 'tid', 'name', 'rate') #2 {main} thrown in/class.php on line 89 
+0

您需要將變量綁定到語句 – Drewdin 2011-06-13 20:49:15

+1

@Drewdin它們被'array()'內部的'$ stmt-> execute()'# – 2011-06-13 20:53:43

回答

2

該錯誤提示列tid是模糊的,因爲它是包含在這兩個你別名a表和b表。要清除它,它需要在SELECT列表中顯示爲a.tidb.tid。通過您的implode()它只能作爲tid進入選擇列表。

解決這個問題的最簡單方法是將所有列的表和列指定爲table.column,並將其作爲函數參數傳入。

或者,你可以在前面加上表像這樣,在做之前implode()

// Assuming all your columns belong to the `a` table alias... 
$arg = func_get_args(); 
$pid = array_shift($arg); 
$prepared_args = array(); 

// Loop over your remaining column name arguments and prepend `a.` to each 
foreach($arg as $a) { 
    $prepared_args = "a.$a" 
} 

$imp = implode(",", $prepared_args); 

// Finish up your PDO stuff... 
+0

隱式綁定有一個語法問題,但除此之外完美。謝謝! – grep 2011-06-13 21:21:47

2

它看起來像$小鬼包含 「TID」。由於兩個表具有tid名稱的列,因此SQL不太確定您希望返回哪個列。 (即使它們兩個應該是相同的。)嘗試在您的$ imp中放入「a.tid」。