可能的重复:
MySQL 插入多个表?(数据库规范化?)
我正在尝试使用 PDO 将我的记录插入到 2 个表中,我有以下内容
im trying to use PDO to insert my records into 2 tables, I have the following
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 个表中?有人可以看看我是否在任何地方出错了吗?
that inserts my data into 1 table fine, if I use (What i presume to be corrct) however my page doesnt render and no source code is output? Can anybody see if im going wrong anywhere?
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();
}
那不是有效的 SQL;你需要分开做.也许:
That’s not valid SQL; you need to do them separately. Maybe:
$sql = "
INSERT INTO `directory`(`First_Name`,`Surname`,`Nicknames`) VALUES (:firstname, :surname, :nicknames);
INSERT INTO `nicknames`(`First_Name`,`Surname`,`Nicknames`) VALUES (:firstname, :surname, :nicknames);
";
这篇关于使用 PDO MySQL 插入 2 个表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!