将数据插入多个表格的功能无法正常运行。

31 浏览
0 Comments

将数据插入多个表格的功能无法正常运行。

我有以下两个表格:

表格 player:

player_id (int)(主键)
player_name (varchar)
player_report_count (int)

表格 report:

report_id (int)(主键)
player_id
report_description
report_location

首先,我会询问用户的 player_name,并将其插入到 player 数据库中。从这里开始,玩家将获得一个id。

然后,我尝试获取玩家的 report count 值,并将当前值增加一(这个操作没有生效)。

接下来,我从 player 表中获取 playerId,并将其插入到 report 表中对应的列中(同样没有生效)。

当我向数据库插入一些值时,姓名、描述和报告会被添加到数据库中,但是所有条目的 playerId 仍然为0,player_report_count 保持为0。

请问如何正确地使这两个功能生效?还有没有更高效的方法来实现这个功能?

prepare("
        INSERT INTO player (player_name)
        VALUES (?)
        ");
        $insertPlayer->bind_param('s', $player_name);
        $reportCount = $db->query("
            UPDATE player
            SET player_report_count = player_report_count + 1
            WHERE
            player_name = $player_name
        ");
        $getPlayerId = $db->query("
        SELECT player_id
        FROM player
        WHERE player_name = $player_name
        ");
        $insertReport = $db->prepare("
        INSERT INTO report (player_id, report_description, report_location)
        VALUES (?, ?, ?)
        ");
        $insertReport->bind_param('iss', $getPlayerId, $report_description, $report_location);
        if($insertPlayer->execute()
        && $insertReport->execute()
        ){
            header('Location: insert.php');
            die();
        }
    }
}

0
0 Comments

问题出现的原因是在插入数据之前获取了player的详细信息,$getPlayerId始终会返回空结果。解决方法如下:

  1. 先将player的详细信息插入到player表中,并用mysql_insert_id获取playerid。在绑定之后,需要执行插入操作。
  2. 然后绑定并执行插入report的操作。
  3. 最后使用步骤1中获取的playerid更新player表,增加report计数。

注意:在插入多个表时使用事务,这样可以在插入失败时回滚。

MySQL查询将返回结果对象。请参考https://stackoverflow.com/a/13791544/3045153

希望对你有帮助。

0
0 Comments

问题原因:在将数据插入到多个表中时,可能无法正确地获得最后插入的数据的ID。这可能是因为没有正确地使用相关函数来获取最后插入的ID。

解决方法:如果使用PDO,则可以使用PDO的lastInsertId()函数来获取最后插入的ID。如果使用自定义的Mysql类,则需要使用mysql_insert_id()函数(或mysqli_insert_id()函数)来获取最后插入的ID,然后直接在下一个INSERT INTO语句中使用它。

0