我想在表字典中插入3行,在表横幅中插入另外3行,因此在本例中,我只为每个表留下了一个查询。
我得到的错误是
无法将类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;

最佳答案

这是修改后的代码,试试这个

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();
}

关于php - 使用PDO和PHP在2个表中插入多行,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55772499/

10-12 16:17