[英]Trying to display in a simple php system mysql data with One to many relationship?
我已經從位置將FirstPositionID / SecondPositionID與PositionID(PRIMARY KEY)連接起來。 每個positionID都有一個職位名稱。 由於我有2個由位置ID設置的玩家位置,所以php不應該打印我設置的每個ID的位置名稱嗎? 當我打印PositionName時,它會打印我已插入到我的位置表中的所有位置。 這是我的桌子
CREATE TABLE `players` (
`PlayerID` int(10) UNSIGNED NOT NULL,
`PlayerName` varchar(255) NOT NULL,
`CountryID` varchar(255) NOT NULL,
`FirstPositionID` int(11) UNSIGNED NOT NULL,
`SecondPositionID` int(10) UNSIGNED NOT NULL,
`Overall` int(11) UNSIGNED NOT NULL,
`Defence` int(11) NOT NULL,
`Speed` int(11) NOT NULL,
`Rebound` int(11) NOT NULL,
`Stamina` int(11) NOT NULL,
`TeamID` int(11) NOT NULL,
`Shooting` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf16;
CREATE TABLE `positions` (
`PositionID` int(10) UNSIGNED NOT NULL,
`PositionName` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf16;
//-----------php-----------------------
$sql= "SELECT * from players,positions";
$reg = mysqli_query($con,$sql);
if(mysqli_num_rows($reg) > 0)
{
while($row = mysqli_fetch_assoc($reg))
{
echo "</br>Player:".$row['PlayerName']." Overall:".$row['Overall']." Position: ".$row['PositionName'];
}
}
else
{
echo "SQL error at: </br> ".$register."SYNTAX:</br>".mysqli_error($con)."</br>";
}
結果:
Player:Agrabanis Overall:64 Position: Point Guard
Player:Athineou Overall:64 Position: Point Guard
Player:Agrabanis Overall:64 Position: Shooting Guard
Player:Athineou Overall:64 Position: Shooting Guard
Player:Agrabanis Overall:64 Position: Small Forward
Player:Athineou Overall:64 Position: Small Forward
Player:Agrabanis Overall:64 Position: Power Forward
Player:Athineou Overall:64 Position: Power Forward
Player:Agrabanis Overall:64 Position: Center
Player:Athineou Overall:64 Position: Center
由於我已經將第一玩家位置ID 5,4和第二玩家位置ID 2,1設置為第一玩家和第二玩家得分后衛,控球后衛(2,1位置),請僅打印Center,Power Forward(4,5位置ID) ids)
請使用left join
或inner join
而不是交叉連接,並將您的SQL字符串更改為類似
SELECT pl.PlayerName, pl.FirstPositionID, pl.Overall,
pl.SecondPositionID, po1.PositionName AS FirstPositionName,
po2.PositionName AS SecondPositionName FROM players pl
LEFT JOIN positions po1 ON(pl.FirstPositionID = po1.PositionID )
LEFT JOIN positions po2 ON (pl.SecondPositionID = po2.PositionID )
LIMIT 0,100
另外,將您的while循環更改為
while($row = mysqli_fetch_assoc($reg)){
echo "</br>Player:".$row['PlayerName']." Overall:".$row['Overall']." Position1: ".$row['FirstPositionName']." Position2:".$row['SecondPositionName '];
}
我認為這將幫助您...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.