PDO Mysql 相同查询但插入到多个用户

PDO Mysql same query but insert to multiple users

我想通过 pdo 插入具有相同值的多个(批量)行,唯一不同的是 user_id

我正在用 userIds 传递一个数组,但我不知道如何绑定它们。

<?php   
    require_once("db.php");

    $usersId = $jsonData["usersId"];
    $text = $jsonData["text"];

    // Try to fetch the user from the database
    $query = "INSERT INTO posts (user_id, text) VALUES (:usersId, :text)";
    $stmt = $db->prepare($query);

    // Bind value
    $stmt->bindValue(":userId", $userId);
    $stmt->bindValue(":text", $text, PDO::PARAM_STR);

    // Execute
    $result = $stmt->execute();
?>

我的表格:

CREATE TABLE users(
    id INT PRIMARY KEY AUTO_INCREMENT,
    name VARCHAR(255)
);

INSERT INTO users (name)
VALUES ("Gregor"),
    ("Liza"),
    ("Matt"),
    ("Bob");
   
CREATE TABLE posts(
    id INT PRIMARY KEY AUTO_INCREMENT,
    user_id INT,
    text VARCHAR(255)
);

你需要一个循环:

    require_once("db.php");

    $text = $jsonData["text"];

    // Try to fetch the user from the database
    $query = "INSERT INTO posts (user_id, text) VALUES (:usersId, :text)";
    $stmt = $db->prepare($query);

    // Bind value
    $stmt->bindParam(":userId", $userId);
    $stmt->bindValue(":text", $text, PDO::PARAM_STR);

    // Execute
    foreach ($jsonData["usersId"] as $userId) {
        $result = $stmt->execute();
    }

使用 bindParam() 以便它绑定到对变量的引用。这允许您每次通过循环重新分配变量而无需 re-binding.