我试图使用一个变量插入到多个表中。当我硬编码特定的表名时,它会正常运行,当我使用一个变量时,我会得到一个查询FAILEDSQLSTATE[42000]:语法错误或访问冲突:1064错误。dbname是变量。我正在使用for循环来更改表的名称。例如,表1是budget1000,然后是Budget2000等等,这是我的代码

$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='INSERT INTO '.$dbName.' VALUES(:id,:category,:subCategory,:amount, :today,:description,   :year)';

关于php - 使用php变量将值插入mysql表,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/7215478/

10-08 22:42
查看更多