可能重复:
MySQL Insert into multiple tables? (Database normalization?)
我试图使用PDO将我的记录插入2个表中,我有以下
try {
// Connect and create the PDO object
$conn = new PDO("mysql:host=$hostdb; dbname=$namedb", $userdb, $passdb);
$conn->exec("SET CHARACTER SET utf8"); // Sets encoding UTF-8
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO `directory` (`First_Name`,`Surname`,`Nicknames`)
VALUES (:firstname, :surname, :nicknames) ";
$statement = $conn->prepare($sql);
$statement->bindValue(":firstname", $firstname);
$statement->bindValue(":surname", $surname);
$statement->bindValue(":nicknames", $nicknames);
$count = $statement->execute();
$conn = null; // Disconnect
}
catch(PDOException $e) {
echo $e->getMessage();
}
将我的数据插入到1个表中,如果我使用(我认为是什么),但是我的页面没有呈现并且没有输出源代码?任何人都可以看到我在哪里出错了吗?
try {
// Connect and create the PDO object
$conn = new PDO("mysql:host=$hostdb; dbname=$namedb", $userdb, $passdb);
$conn->exec("SET CHARACTER SET utf8"); // Sets encoding UTF-8
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO `directory`, `nicknames` (`First_Name`,`Surname`,`Nicknames`)
VALUES (:firstname, :surname, :nicknames) ";
$statement = $conn->prepare($sql);
$statement->bindValue(":firstname", $firstname);
$statement->bindValue(":surname", $surname);
$statement->bindValue(":nicknames", $nicknames);
$count = $statement->execute();
$conn = null; // Disconnect
}
catch(PDOException $e) {
echo $e->getMessage();
}
答案 0 :(得分:7)
这不是有效的SQL;你需要分开做。也许:
$sql = "
INSERT INTO `directory`(`First_Name`,`Surname`,`Nicknames`) VALUES (:firstname, :surname, :nicknames);
INSERT INTO `nicknames`(`First_Name`,`Surname`,`Nicknames`) VALUES (:firstname, :surname, :nicknames);
";
答案 1 :(得分:0)
据我所知,你不能用一个mySQL查询插入2个表。相反,您应该使用两个不同的查询。
答案 2 :(得分:0)
问题在于SQL,我不相信它是有效的语法。我认为在这种情况下你需要一个交易。