2013-07-29 44 views
2

運行到我看不到的問題。PHP PDO語法錯誤或訪問衝突:1064

這裏是我的功能

function addIT($type, $amount, $id) { 
$db = new database(); 
$conn8 = $db->connect(); 
$addit = $conn8->prepare("UPDATE accountTable SET :type = :type + :amount WHERE ID =  :id"); 
$addit->execute(array('type'=>$type, 'amount'=>$amount, 'id'=>$id)); 
} 

繼承人的電話我做:

$type = "age"; 
$amount = 17; 
$id = 1; 
addIT($type, $amount, $id); 
現在

當執行它給了我下面的錯誤

Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''age' = 'age' + '17' WHERE ID = '1'' at line 1' in /Library/WebServer/Documents/me/functions/activity.php:7 Stack trace: #0 /Library/WebServer/Documents/me/functions/activity.php(7): PDOStatement->execute(Array) #1 /Library/WebServer/Documents/me/content/doadd.php(66): addIT('age', 17, '1') #2 /Library/WebServer/Documents/me/main(48): include('/Library/WebSer...') #3 /Library/WebServer/Documents/me/where.php(25): include('/Library/WebSer...') #4 {main} thrown in /Library/WebServer/Documents/me/functions/activity.php on line 7 

的代碼,我敢肯定,有件事我的執行或準備聲明中出現錯誤。我再也看不到它了。

+0

在查詢中不能有變量列或表名 –

+0

根本不應該有$ conn8變量。以及任何其他$ connN –

回答

2
function addIT($conn, $type, $amount, $id) 
{ 
    $allowed = array('age','sex','whatever'); 
    if (!in_array($type,$allowed)) 
    { 
     throw new Exception("Invalid type"); 
    } 
    $sql = "UPDATE accountTable SET `$type` = `$type` + :amount WHERE ID = :id" 
    $stm = $conn->prepare($sql); 
    $stm->execute(array('amount'=>$amount, 'id'=>$id)); 
} 
+0

完美的解決方法!也適用。而且因爲我正在尋找一個動態的解決方案,所以這最符合我的問題。 – Ray

+1

他們應該在PDO中真正具備這個功能,因爲這些解決方案總是令人擔憂。 – tadman

+0

是真的,有點拿走PDO應該帶來的安全 – Ray

4

在查詢中不能包含變量列或表名。使用

UPDATE accountTable 
SET age = age + :amount 
WHERE ID = :id 

順便說一句,你不應該存儲一個人的年齡,而是存儲出生日期。那麼你不必更新它。

+0

好的很多,我們不會使用動態列。 – Ray

相關問題