尝试使用一个查询将两个INSERT添加到两个不同的数据库表中

时间:2015-08-13 15:02:53

标签: php mysql sql insert

我试图将完全相同的信息发送到两个不同的表。我读过一个INSERT查询无法做到这一点,所以我尝试这样做。

 $stmt2 = $con->prepare("INSERT INTO user_players (user_id, firstname, lastname, username, email) VALUES (?, ?, ?, ?, ?)");
    $stmt2 = $con->prepare("INSERT INTO drafted_players (user_id, firstname, lastname, username, email) VALUES (?, ?, ?, ?, ?)");

    if ( false===$stmt2 ) {
         // Check Errors for prepare
        die('Add to user players prepare() failed: ' . htmlspecialchars($con->error));
    }
    $stmt2->bind_param('issss', $shuffle_id, $shuffle_firstname, $shuffle_lastname, $shuffle_username, $shuffle_email);

    foreach ($_POST['id'] as $i => $shuffle_id) {
        $shuffle_firstname = $_POST['firstname'][$i];
        $shuffle_lastname = $_POST['lastname'][$i];
        $shuffle_username = $_POST['username'][$i];
        $shuffle_email = $_POST['email'][$i];
        $stmt2->execute() or
            die('Add to user players execute() failed: ' . htmlspecialchars($stmt2->error));

只有第二个插入部分正在工作。我如何构建这个,以便INSERT的工作?

2 个答案:

答案 0 :(得分:1)

您要分配$stmt2两次 - 如果您有两个预准备语句,则需要两个变量来存储它们。如果您将代码更改为:

$stmt1 = $con->prepare("INSERT INTO user_players (user_id, firstname, lastname, username, email) VALUES (?, ?, ?, ?, ?)");
$stmt2 = $con->prepare("INSERT INTO drafted_players (user_id, firstname, lastname, username, email) VALUES (?, ?, ?, ?, ?)");

if ( false===$stmt1 || false===$stmt2 ) {
     // Check Errors for prepare
    die('Add to user players prepare() failed: ' . htmlspecialchars($con->error));
}
$stmt1->bind_param('issss', $shuffle_id, $shuffle_firstname, $shuffle_lastname, $shuffle_username, $shuffle_email);
$stmt2->bind_param('issss', $shuffle_id, $shuffle_firstname, $shuffle_lastname, $shuffle_username, $shuffle_email);

foreach ($_POST['id'] as $i => $shuffle_id) {
    $shuffle_firstname = $_POST['firstname'][$i];
    $shuffle_lastname = $_POST['lastname'][$i];
    $shuffle_username = $_POST['username'][$i];
    $shuffle_email = $_POST['email'][$i];
    $stmt1->execute() or
        die('Add to user players execute() failed: ' . htmlspecialchars($stmt1->error));
    $stmt2->execute() or
        die('Add to user players execute() failed: ' . htmlspecialchars($stmt2->error));

它应该有用。

答案 1 :(得分:0)

您也可以在一个语句中发送这两个命令(最好使用命名参数)

$statement = $con->prepare("INSERT INTO user_players    (user_id, firstname, lastname, username, email) VALUES (:user_id, :firstname, :lastname, :username, :email);  
                            INSERT INTO drafted_players (user_id, firstname, lastname, username, email) VALUES (:user_id, :firstname, :lastname, :username, :email);");

$statement->bindValue('user_id', $shuffle_id);
...