简体   繁体   English

使用php变量将值插入mysql表

[英]Using a php variable to insert values into a mysql table

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. 当我对特定的表名进行硬编码时,它可以正常运行,当我使用变量时,会出现QUERY FAILEDSQLSTATE [42000]:语法错误或访问冲突:1064错误。 dbname is the variable. dbname是变量。 I am using a for loop to change the name of the table. 我正在使用for循环来更改表的名称。 For example table 1 is budget1000, then budget 2000 etc. Here is my code 例如表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();

} }

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周围的句点,或者一直使用单引号。

试试这个:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM