我有以下两个表
表球员:player_id (int)(primary)
player_name (varchar)
player_report_count (int)
表报告:report_id (int)(primary)
player_id
report_description
report_location
首先,我向用户询问player_name并将其插入播放器数据库。从这里开始,玩家将获得一个id。
然后我试图抓住玩家报告计数的值,并将当前值增加一个(这不起作用)。
接下来是从播放器表中抓取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();
}
}
}
这里的主要问题是你在插入它之前获得了玩家的详细信息。$getPlayerId将始终返回空结果。
请按下列顺序来做。
-
将球员详细信息插入到球员表中,并使用mysql_insert_id获取payerid。绑定后,需要执行将详细信息插入到表中。
-
然后绑定并执行插入报告
-
然后通过增加在第1步中得到的playerid的报告计数来更新播放器表
注意:插入多个表时使用事务。这将帮助您在任何插入失败时回滚。
MySQL查询将返回结果对象。参考这里https://stackoverflow.com/a/13791544/3045153
希望对你有帮助
如果你需要捕获最后插入球员的ID,这是你需要的函数,如果你使用PDO或如果它是一个自定义Mysql类,你需要mysql_insert_id()(或mysqli_insert_id())的返回值,然后直接使用它在下一个INSERT INTO
语句