[英]Using a php variable to insert values into a mysql table
我正在嘗試使用變量插入多個表。 當我對特定的表名進行硬編碼時,它可以正常運行,當我使用變量時,會出現QUERY FAILEDSQLSTATE [42000]:語法錯誤或訪問沖突:1064錯誤。 dbname是變量。 我正在使用for循環來更改表的名稱。 例如表1是budget1000,然后是預算2000,等等。這是我的代碼
$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();
}
看起來好像有一個引號不匹配,您以單引號開始,但是在將數據庫名稱連接到字符串中時切換為雙引號。 嘗試用雙引號替換$ sql字符串開頭和結尾的單引號,並刪除$ dbname周圍的句點,或者一直使用單引號。
試試這個:
$sql='INSERT INTO '.$dbName.' VALUES(:id,:category,:subCategory,:amount, :today,:description, :year)';
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.