使用php变量将值插入mysql表

时间:2022-09-25 16:09:15

I am trying to use a variable to insert into multiple tables. When I hard code the specific table name it runs properly, when I use a variable I get a QUERY FAILEDSQLSTATE[42000]: Syntax error or access violation: 1064 error. dbname is the variable. I am using a for loop to change the name of the table. For example table 1 is budget1000, then budget 2000 etc. Here is my code

我试图使用变量插入多个表。当我硬编码它正确运行的特定表名时,当我使用变量时,我得到一个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();

}

}

2 个解决方案

#1


1  

Try this instead:

试试这个:

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

#2


2  

It looks like there's a quote mismatch, you start off with single quotes but then switch to double quotes when you concatenate the DB name into your string. Try replacing the single quotes at the beginning and end of your $sql string with double quotes and remove the periods around $dbname, or use single quotes all the way through.

看起来有一个引用不匹配,你从单引号开始,但是当你将数据库名称连接到字符串时切换到双引号。尝试用双引号替换$ sql字符串开头和结尾的单引号,并删除$ dbname周围的句点,或者一直使用单引号。

#1


1  

Try this instead:

试试这个:

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

#2


2  

It looks like there's a quote mismatch, you start off with single quotes but then switch to double quotes when you concatenate the DB name into your string. Try replacing the single quotes at the beginning and end of your $sql string with double quotes and remove the periods around $dbname, or use single quotes all the way through.

看起来有一个引用不匹配,你从单引号开始,但是当你将数据库名称连接到字符串时切换到双引号。尝试用双引号替换$ sql字符串开头和结尾的单引号,并删除$ dbname周围的句点,或者一直使用单引号。