PHP数据库查询以html格式显示

时间:2013-12-01 01:54:19

标签: php html mysql post

我不是一个耐心的编码员。我现在正在学习php / htmp / mysql / css:)

所以,我用php进行mysql查询,现在我想在html表中显示查询结果。但我不知道,我怎样才能在php和html代码之间传递变量。

我的php文件现在看起来像这样:

<?php

$con=mysqli_connect("my_db_host","my_db_username","my_db_pass","my_db_name");

if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$result = mysqli_query($con,"SELECT * FROM hlstats_Servers
WHERE serverId='2'");

while($row = mysqli_fetch_array($result))
{
$name=$row['name'];
$ip=$row['address'] . ":" . $row['port'];
$player=$row['act_players'] . "/" . $row[max_players];
$map=$row['act_map'];
}    

mysqli_close($con);
?>

<html>
<head>
</head>
    <body>
        <table>
              <tr>
                  <td>$name</td>
              </tr>
        </table>

        <table>
              <tr>
                  <td>Ip cím:</td>
                  <td>$ip</td>
              </tr>
              <tr> 
                  <td>Jelenlegi pálya:</td>
                  <td>$map</td>
              </tr>
              <tr>
                  <td>Játékosok</td>
                  <td>$player</td>
              </tr> 
          </table>
      </body>
</html>

2 个答案:

答案 0 :(得分:1)

Sok sikert(祝你好运):)

<?php
    $con = mysqli_connect("my_db_host", "my_db_username", "my_db_pass", "my_db_name");

    if (mysqli_connect_errno()) {
        echo "Failed to connect to MySQL: " . mysqli_connect_error();
    }

    $result = mysqli_query(
        $con,
        "SELECT * FROM hlstats_Servers
        WHERE serverId='2'"
    );
?>

<html>
    <head></head>
    <body>
        <table>
            <?php while ($row = mysqli_fetch_array($result)): ?>
                <?php $name = $row['name']; ?>
                <?php $ip = $row['address'] . ":" . $row['port']; ?>
                <?php $player = $row['act_players'] . "/" . $row['max_players']; ?>
                <?php $map = $row['act_map']; ?>

                <tr>
                    <td colspan="2"><?php echo $name; ?></td>
                </tr>
                <tr>
                    <td>Ip cím:</td>
                    <td><?php echo $ip; ?></td>
                </tr>
                <tr>
                    <td>Jelenlegi pálya:</td>
                    <td><?php echo $map; ?></td>
                </tr>
                <tr>
                    <td>Játékosok</td>
                    <td><?php echo $player; ?></td>
                </tr>
            <?php endwhile; ?>
        </table>
    </body>
</html>

<?php mysqli_close($con); ?>

答案 1 :(得分:0)

您无法将变量从PHP代码“转移”到HTML代码,因为后者不是编程语言,它只是描述没有变量或过程的网页的结构化标记语言。

相反,您可以显示PHP变量的当前值,然后HTML标记将包含该变量的实际值。例如:

<table>
      <tr>
          <td><?php echo $name; ?></td>
      </tr>
</table>