本文介绍了使用PDO MySQL插入2个表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正尝试使用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个表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!