简体   繁体   English

如何减少我的php代码来循环html表代码?

[英]How can I reduce my php code to loop my html table code?

I am hoping someone can help me with my php coding. 我希望有人可以帮助我进行php编码。 Here is what I am attempting to do: 这是我正在尝试做的事情:

I run a video game club at my high school and we have 121 members this year (biggest club in a school of ~900 students). 我在高中时经营着一个视频游戏俱乐部,今年我们有121名成员(这是一个有900名学生的学校中最大的俱乐部)。 Retrogaming has been a hit with many of them and it had led to the discussion of having leaderboards. Retrogaming在其中很多人中都很受欢迎,这引发了关于拥有排行榜的讨论。 So early on I realized that constantly updating an HTML file would be rediculous and decided to setup a mysql database where high score attempts could be entered into a form (by me only) and populated to a webpage. 因此,我很早就意识到不断更新HTML文件是多余的,因此决定建立一个mysql数据库,在该数据库中,可以将高分的尝试输入表单(仅由我自己)并填充到网页中。 Said webpage has a table for each game title, along with top 3 scores in the database. 所述网页具有用于每个游戏标题的表格,以及数据库中的前3个得分。 This part is working very well so far. 到目前为止,这部分效果很好。 My database schema goes something like this: 我的数据库架构如下所示:

Table 1 ("gamesystems"): 表1(“游戏系统”):

  • gamesystems_id (primary key, AI) gamesystems_id(主键,AI)
  • gamesystems (varchar(30)) (eg Atari 2600, NES, Colecovision, etc.) 游戏系统(varchar(30))(例如Atari 2600,NES,Colecovision等)

Table 2: ("games") 表2 :(“游戏”)

  • games_id (primary key, AI) games_id(主键,AI)
  • gamesystems_id (foreign key) gamesystems_id(外键)
  • game (varchar(30)) (eg Frogger, Crazy Taxi, etc) 游戏(varchar(30))(例如Frogger,Crazy Taxi等)

Table 3: ("solo_leaderboard") 表3 :(“ solo_leaderboard”)

  • id (primary key, AI) id(主键,AI)
  • gamesystem (varchar(30)) 游戏系统(varchar(30))
  • game (varchar(30)) 游戏(varchar(30))
  • name (varchar(30)) 名称(varchar(30))
  • score (int(10)) 得分(int(10))
  • date (date) 日期(日期)
  • gradelevel (varchar(5)) (varchar is to accomidate N/A if not a student) gradelevel(varchar(5))(如果不是学生,则varchar要适应N / A)
  • whois (enum('student', 'teacher', 'administrator', 'other')) whois(枚举(“学生”,“老师”,“管理员”,“其他”))

Okay. 好的。 Perhaps not perfect, but this schema works for now. 也许不是完美的,但是这种模式目前仍然有效。 I can add data and pull data, and post it to my php page on my website. 我可以添加数据和提取数据,并将其发布到我的网站上的php页面。 Below is the code for just 2 games that I have posted right now. 以下是我现在发布的仅2个游戏的代码。 The issue should be obvious; 这个问题应该很明显。 I have to add 30+ lines of code for each new game that I want to post the high scores for. 对于要发布高分的每个新游戏,我必须添加30多行代码。 This is rediculous. 这太可笑了。 I don't have a strong mysql or php background, but I spent a lot of time coding C++ and Python years and years ago. 我没有强大的mysql或php背景,但是几年前我花了很多时间编码C ++和Python。 I think that there should be a way to have a NESTED loop that pulls each gaming system (table 1) one-by-one and creates a table for each game (table 2) for said system and populates the webpage with the top 3 scores from the solo-leaderboard (table 3). 我认为应该有一种方法可以使NESTED循环一个接一个地拉动每个游戏系统(表1),并为该系统为每个游戏创建一个表(表2),并用前3个得分填充网页来自排行榜(表3)。 Unfortunately, I don't know how to make this happen. 不幸的是,我不知道该如何实现。 That is why I am here. 这就是为什么我在这里。 Any ideas? 有任何想法吗?

<?php
$servername="localhost";
$username="strickho_leader";
$password="***********";
$database="strickho_leaderboards";

echo "
<body style='background-color:powderblue'; 'text-align:center';>
<h1 style='color:black'; 'font-size:300%'; 'text-align:center';>Benton Central M.A.G.I. Gaming Leaderboard</h1>
</body>";

//Create Connection
$conn = new mysqli($servername, $username, $password, $database);

//FREEWAY
//*****************************************
$result = mysqli_query($conn,"SELECT * FROM solo_leaderboard WHERE game LIKE '%Freeway%' ORDER BY score DESC LIMIT 3");

echo "<table style='text-align:center'; border='1';>
<tr>
<th colspan='5'>Freeway</th>
</tr>
<tr>
<th colspan='5'><img src='https://www.mobygames.com/images/covers/l/20735-freeway-atari-2600-front-cover.jpg' height='200' width='145'></th>
</tr>
<tr>
<th>Name</th>
<th>Score</th>
<th>Date</th>
<th>Grade</th>
<th>Role</th>
</tr>";

while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['name'] . "</td>";
echo "<td><b>" . $row['score'] . "</b></td>";
echo "<td>" . $row['date'] . "</td>";
echo "<td>" . $row['gradelevel'] . "</td>";
echo "<td>" . $row['whois'] . "</td>";
echo "</tr>";
}
echo "</table><br><br>";
//*******************************************
//END FREEWAY


//CRAZY TAXI
//*****************************************
$result = mysqli_query($conn,"SELECT * FROM solo_leaderboard WHERE game LIKE '%Crazy Taxi%' ORDER BY score DESC LIMIT 3");

echo "<table style='text-align:center'; border='1';>
<tr>
<th colspan='5'>Crazy Taxi</th>
</tr>
<tr>
<th colspan='5'><img src='https://www.mobygames.com/images/covers/l/5801-crazy-taxi-dreamcast-front-cover.jpg' height='200' width='200'></th>
</tr>
<tr>
<th>Name</th>
<th>Score</th>

Instead of making one query per game, you could make one general query that retrieves data for all games and then loop through it. 可以对每个游戏检索数据,然后循环遍历,而不是对每个游戏进行一次查询。 It's two queries actually but those two queries should handle all the work. 实际上是两个查询,但是那两个查询应该处理所有工作。 My proposal requires some changes to your tables, I'll walk you through it. 我的建议要求对您的表进行一些更改,我将逐步指导您进行操作。

FIRST QUERY: 第一查询:

SELECT * from games

Just the games table. 只是games桌。 Nothing else. 没有其他的。 Then take that result (it'll be one game per row) and loop through it with a foreach: 然后取得该结果(每行一场),并通过foreach遍历该结果:

foreach ($games as $game)

(I used $games , but use the variable with actually gets the query result) Now that you're looping through the games, make a second query (within the loop) to get the leaderboard for that specific game. (我使用$games ,但实际上使用变量来获取查询结果)既然您正在遍历游戏,请再次查询(在循环内)以获取该特定游戏的排行榜。

SECOND QUERY: 第二查询:

SELECT * FROM solo_leaderboard WHERE game LIKE '%game_name_from_previous_query%' ORDER BY score DESC LIMIT 3

My suggestion here is not to search using LIKE as it is less efficient, even though it will work. 我的建议是不要使用LIKE进行搜索,因为它虽然效率较低,但效率较低。 My suggestion would be to alter the solo_leaderboard table to include the game id so you can search with WHERE game_id = the_id_from_the_previous_query 我的建议是更改solo_leaderboard表以包含游戏ID,以便您可以使用WHERE game_id = the_id_from_the_previous_query搜索

Finally, without exiting the outermost foreach loop, you can loop through the second query's results and draw the table as you are doing now. 最后,无需退出最外层的foreach循环,就可以循环浏览第二个查询的结果并像现在一样绘制表。

That's the general idea. 那是一般的想法。 This will loop through all the games, get each game's leaderboard and output it to a table, then move on to the next game and so on 这将循环遍历所有游戏,获取每个游戏的排行榜并将其输出到桌子,然后继续进行下一个游戏,依此类推

It has been a long time since I used PHP, but I will try to help, it's possible I misspell some PHP terms or functions. 自从我使用PHP已有很长时间了,但是我会尽力提供帮助,可能我拼错了一些PHP术语或函数。

First advice, it's better to write html static content directly instead of doing echo , every piece of php code you write is going to be processed by your server, an echo has low impact but 1k's of long html echo are worst than zero. 首先建议,最好直接编写html静态内容而不是执行echo ,您编写的每段php代码都将由服务器处理, echo影响很小,但是1k的长html echo的值比零还差。 So, instead of: 因此,代替:

<?php
    $servername="localhost";
    $username="strickho_leader";
    $password="***********";
    $database="strickho_leaderboards";

    echo "<body style='background-color:powderblue'; 'text-align:center';>
<h1 style='color:black'; 'font-size:300%'; 'text-align:center';>Benton Central M.A.G.I. Gaming Leaderboard</h1>
</body>";

    //Create Connection
    $conn = new mysqli($servername, $username, $password, $database);

You should do: 你应该做:

<?php
    $servername="localhost";
    $username="strickho_leader";
    $password="***********";
    $database="strickho_leaderboards";
?>

<body style='background-color:powderblue'; 'text-align:center';>
<h1 style='color:black'; 'font-size:300%'; 'text-align:center';>Benton Central M.A.G.I. Gaming Leaderboard</h1>
</body>

<?php
    //Create Connection
    $conn = new mysqli($servername, $username, $password, $database);

And If you are using a nice web development editor you will get html syntax highligth in this way. 并且,如果您使用的是一个不错的Web开发编辑器,则将以这种方式获得html语法highligth。 When you have to print php values inside html code you can open an php code tag and make a single var echo . 当您必须在html代码中打印php值时,可以打开一个php代码标签并进行单个var echo

Starting with your answer, of course you can make nested loops. 从您的答案开始,您当然可以进行嵌套循环。 First of all, I think you should change your data model, if leaderboards are different for everygame you should have games_id in the leaderboard table instead of game name. 首先,我认为您应该更改数据模型,如果每个游戏的排行榜都不同,则排行榜表中应该包含games_id而不是游戏名称。

So your code could look like this: 因此您的代码可能如下所示:

<?php
    $LEADER_TOP = 3;
    $servername="localhost";
    $username="strickho_leader";
    $password="***********";
    $database="strickho_leaderboards";
?>

<body style='background-color:powderblue'; 'text-align:center';>
<h1 style='color:black'; 'font-size:300%'; 'text-align:center';>Benton Central M.A.G.I. Gaming Leaderboard</h1>

<?php
    //Create Connection
    $mysqli = new mysqli($servername, $username, $password, $database);

    /* Check connection (from docs) */
    if (mysqli_connect_errno()) {
        printf("Connection error: %s\n", $mysqli->connect_error);
        exit();
    }

    //All games
    $query = "SELECT * FROM games ORDER BY game ASC";

    if ($games = $mysqli->query($query)) {

        // Get single game
        while ($game = $games->fetch_assoc()) {         
            // Print game table
?>

<table style='text-align:center'; border='1';>
    <tr>
        <th colspan='5'><?php echo $game['game']; ?></th>
    </tr>
    <tr>
        <th colspan='5'><img src="<?php echo $game['image']; ?>" height='200' width='145'></th>
    </tr>
    <tr>
        <th>Name</th>
        <th>Score</th>
        <th>Date</th>
        <th>Grade</th>
        <th>Role</th>
    </tr>

<?php
            // Get leaders
            $query = "SELECT * FROM solo_leaderboard WHERE game_id = '"+ $game['games_id'] +"' ORDER BY score DESC LIMIT "+$LEADER_TOP;
            if ($leaders = $mysqli->query($query)) {
                while ($leader = $leaders->fetch_assoc()) {
?>
    <tr>
        <td><?php echo $leader['name']; ?></td>
        <td><b><?php echo $leader['score']; ?></b></td>
        <td><?php echo $leader['date']; ?></td>
        <td><?php echo $leader['gradelevel']; ?></td>
        <td><?php echo $leader['whois']; ?></td>
    </tr>
<?php
                } // END While Leaders

                // Free leaders
                $leaders->free();
            }
?>
</table><br><br>
<?php
        } // END While Games

        // Free games
        $games->free();
    }
?>

As you can see, you need to add the image url to your game model and change the game name to games_id in leaderboards. 如您所见,您需要将图像网址添加到游戏模型中, games_id排行榜中的游戏名称更改为games_id

Another personal advice, use always doubleqoute in html attributes: src="xxx" . 另一个个人建议,请在html属性中始终使用doubleqoute: src="xxx"

Good luck! 祝好运!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM