将数据插入多个表格无法正常运行

时间:2015-08-07 01:06:44

标签: php mysql

我有以下两个表

表格播放器:

player_id (int)(primary)
player_name (varchar)
player_report_count (int)

表格报告:

report_id (int)(primary)
player_id
report_description
report_location

首先,我向用户询问player_name并将其插入播放器数据库。从这里给玩家一个id。

然后我试图获取玩家报告计数的值并将当前值增加1(这不起作用)。

然后从播放器表中抓取playerId,然后从报告表中插入相应的列(也不起作用)。

当我将一些值插入数据库时​​,名称,描述和报告将添加到数据库中,但是对于所有条目,playerID保持为0,并且player_report_count保持一致的0。

使这两个功能正常运行的正确方法是什么?还有一种更有效的方法吗?

<?php
$records = array();

if(!empty($_POST)){
if(isset($_POST['player_name'],
    $_POST['report_description'],
    $_POST['report_location'])){

    $player_name = trim($_POST['player_name']);
    $report_description = trim($_POST['report_description']);
    $report_location = trim($_POST['report_location']);

    if(!empty($player_name) && !empty($report_description) && !empty($report_location)){
        $insertPlayer = $db->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();
        }


    }


}

2 个答案:

答案 0 :(得分:3)

Main issue here is you are getting player details before inserting it. $getPlayerId will return empty result always.

Please follow the order as follows.

  1. Insert player details in to player table and get payerid with mysql_insert_id. After binding you need to execute to insert details to the table.

  2. Then bind and execute insert report .

  3. Then update the player table by incrementing report count with playerid which you got in step 1.

Note : use transactions when inserting multiple table. This will help you to rollback if any insert fails.

MySQL Query will return result object. Refer it from here https://stackoverflow.com/a/13791544/3045153

I hope it will help you

答案 1 :(得分:1)

如果你需要捕获最后一个被攻击的玩家的ID,This is the function you need如果你正在使用PDO或者它是一个自定义的Mysql类,你需要mysql_insert_id()(或mysqli_insert_id())的返回值然后在下一个INSERT INTO语句中直接使用它