使用PDO和PHP在2个表中插入多行

时间:2019-04-20 10:18:23

标签: php mysql pdo

我想在表字典中插入3行,并在表标题中插入另外3行,因此在此示例中,我仅对每个表保留1个查询。 我遇到的错误是

  

PDOStatement类的对象无法转换为字符串

try {
$conn = new PDO('mysql:host=mysql;dbname=mydb;charset=utf8mb4', 'root', 'tiger');
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->beginTransaction();

$conn->exec("INSERT INTO `dictionary` (`id`, `it`, `en`, `fr`, `es`, `pt`, `de`, `nl`) VALUES ('1', 'Sed tempus libero a tristique placerat.\r\n', 'Curabitur at justo sit amet mi aliquam vestibulum.\r\n', 'Duis sed elit suscipit, venenatis ipsum vitae, molestie elit.\r\n', 'Ut ac tortor semper, finibus est ac, porta erat.\r\n', 'Morbi sit amet quam facilisis, tristique mi a, sagittis quam.\r\n', 'Nulla nec sem quis velit tristique tempus vel id augue.\r\n', 'Mauris tincidunt leo eget tincidunt bibendum.\r\n')");
echo "New dictionary created successfully";

$stmt = $conn->prepare("INSERT INTO `banner` (`id`, `dictionaryId`, `name`, `destinationURL`, `domains`, `imageURL`, `position`, `startDate`, `finishDate`) VALUES ('5', '1', 'blink', 'github.com', 'Github', :imageURL, '5', '2019-04-18 03:00:00', '2019-05-04 00:00:00')");
$stmt->bindValue(':imageURL', $dropboxLink);
$stmt->execute();
$conn->commit();
echo "New banner created successfully";
} catch (PDOException $e) {
echo $stmt . "<br>" . $e->getMessage();
}

$conn = null;

1 个答案:

答案 0 :(得分:1)

这是修改后的代码,请尝试

try {
  $conn = new PDO('mysql:host=mysql;dbname=mydb;charset=utf8mb4', 'root', 'tiger');
  $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  $conn->beginTransaction();

  $stmt1 = $conn->prepare("INSERT INTO `dictionary` (`id`, `it`, `en`, `fr`, `es`, `pt`, `de`, `nl`) VALUES ('1', 'Sed tempus libero a tristique placerat.\r\n', 'Curabitur at justo sit amet mi aliquam vestibulum.\r\n', 'Duis sed elit suscipit, venenatis ipsum vitae, molestie elit.\r\n', 'Ut ac tortor semper, finibus est ac, porta erat.\r\n', 'Morbi sit amet quam facilisis, tristique mi a, sagittis quam.\r\n', 'Nulla nec sem quis velit tristique tempus vel id augue.\r\n', 'Mauris tincidunt leo eget tincidunt bibendum.\r\n')");
  $stmt1->execute();
  echo "New dictionary created successfully";

  $stmt2 = $conn->prepare("INSERT INTO `banner` (`id`, `dictionaryId`, `name`, `destinationURL`, `domains`, `imageURL`, `position`, `startDate`, `finishDate`) VALUES ('5', '1', 'blink', 'github.com', 'Github', :imageURL, '5', '2019-04-18 03:00:00', '2019-05-04 00:00:00')");
  $stmt2->bindValue(':imageURL', $dropboxLink);
  $stmt2->execute();
  $conn->commit();
  echo "New banner created successfully";
} catch (PDOException $e) {
 echo $e->getMessage();
}