[英]How I pass the id from one table in a row in another table?
我正在生成一些足球器材,我想做的就是将这些器材和比赛插入两张桌子。 夹具表是不错的选择,但是我很难在“匹配”表中插入匹配项,因为该表具有“夹具”表的外键。
id_fixture unsigned bigint(20)
fixture bigint(20)
id_match unsigned bigint(20)
fixture bigint(20) -> foreign key to fixture.id_fixture
homeTeam varchar(191)
awayTeam varchar(191)
$i = 1;
foreach ($games as $rounds) {
$free = "";
echo "<h5>Etapa {$i}</h5>";
$SQL1 = "INSERT INTO `fixture` (`id_fixture`, `fixture`) VALUES (NULL, '$i');";
$query1 = $link->query($SQL1);
foreach ($rounds as $match) {
if ($match[0] == "stă etapa asta.") {
$free = "<span style='color:red;'>{$match[1]} {$match[0]}</span><br>";
$SQL2 = "INSERT INTO `match` (`id_match`, `fixture`, `homeTeam `, `awayTeam `) VALUES (NULL, '$match[1]', '$match[0]');";
$query2 = $link->query($SQL2);
} elseif ($match[1] == "stă etapa asta.") {
$free = "<span style='color:red;'>{$match[0]} {$match[1]}</span><br>";
$SQL3 = "INSERT INTO `match` (`id_match`, `fixture`, `homeTeam `, `awayTeam `) VALUES (NULL, '$match[0]', '$match[1]');";
$query3 = $link->query($SQL3);
} else {
echo "{$match[0]} vs {$match[1]}<br>";
$SQL4 = "INSERT INTO `match` (`id_match`, `fixture`, `homeTeam `, `awayTeam `) VALUES (NULL, '$match[0]', '$match[1]');";
$query4 = $link->query($SQL4);
}
}
echo $free;
echo "<br>";
$i++;
}
mysqli_close($link);
生成游戏时,如何将fixture.id_fixture传递给match.fixture?
您可以使用$link->insert_id
。
$i = 1;
foreach ($games as $rounds) {
$free = "";
echo "<h5>Etapa {$i}</h5>";
$stmt = $link->prepare('INSERT INTO fixture (fixture) VALUES (?)');
$stmt->bind_param('i', $i);
$stmt->execute();
$id_fixture = $link->insert_id; // The auto generated ID
foreach ($rounds as $match) {
if ($match[0] == "stă etapa asta.") {
$free = "<span style='color:red;'>{$match[1]} {$match[0]}</span><br>";
$stmt = $link->prepare('INSERT INTO `match` (fixture, homeTeam, awayTeam) VALUES (?, ?, ?)');
$stmt->bind_param('iss', $id_fixture, $match[1], $match[0]);
$stmt->execute();
} elseif ($match[1] == "stă etapa asta.") {
$free = "<span style='color:red;'>{$match[0]} {$match[1]}</span><br>";
$stmt = $link->prepare('INSERT INTO `match` (fixture, homeTeam, awayTeam) VALUES (?, ?, ?)');
$stmt->bind_param('iss', $id_fixture, $match[0], $match[1]);
$stmt->execute();
} else {
echo "{$match[0]} vs {$match[1]}<br>";
$stmt = $link->prepare('INSERT INTO `match` (fixture, homeTeam, awayTeam) VALUES (?, ?, ?)');
$stmt->bind_param('iss', $id_fixture, $match[0], $match[1]);
$stmt->execute();
}
}
echo $free;
echo "<br>";
$i++;
}
我从您的查询中删除了ID
列,因为我假设它们都是自动生成的ID,在这种情况下,您不需要为每个参数传递NULL。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.