2011-08-27 81 views
1

我想用變量插入到多個表中。當我硬編碼特定的表名稱時,它運行正常,當我使用一個變量時,我得到一個QUERY FAILEDSQLSTATE [42000]:語法錯誤或訪問衝突:1064錯誤。 dbname是變量。我正在使用for循環來更改表的名稱。例如表1是budget1000,則預算2000等。這裏是我的代碼使用php變量將值插入到mysql表中

$sql='INSERT INTO ".$dbName." VALUES(:id,:category,:subCategory, 
:amount, :today,:description, :year)'; 


try{ 
$st= $conn->prepare($sql); 
$st->bindValue(":id", $id, PDO::PARAM_INT); 
$st->bindValue(":category", $category, PDO::PARAM_INT); 
$st->bindValue(":subCategory", $subCategory, PDO::PARAM_INT); 
$st->bindValue(":amount", $amount, PDO::PARAM_INT); 
$st->bindValue(":today", $today, PDO::PARAM_STR); 
$st->bindValue(":description", $description, PDO::PARAM_STR); 
$st->bindValue(":year", $year, PDO::PARAM_INT); 
$st->execute(); 
}catch(PDOException $e){ 
echo "QUERY FAILED" . $e->getMessage(); 

}

+0

你應該只使用一個表,而不是一堆 –

回答

1

試試這個:

$sql='INSERT INTO '.$dbName.' VALUES(:id,:category,:subCategory,:amount, :today,:description, :year)'; 
+0

感謝您的例子。從雙引號更改爲單引號,它的工作。 – Aaron

2

它看起來像有一個報價不匹配,你開始用單引號,但然後切換到雙引號,當你將DB名稱連接到您的字符串中。嘗試用雙引號替換$ sql字符串開始和結尾處的單引號,並刪除$ dbname周圍的句點,或者一直使用單引號。