如何使用bootstrap css表来显示MySQL表中的数据?

时间:2014-07-20 21:51:31

标签: php html mysql css

我试图这样做,以便当我在主页上单击一个按钮时,php脚本会执行操作并从SQL表中获取信息,并将其显示在HTML / CSS表中。

这是我的主页代码 -

<form id="myForm" action="select.php" method="post">
<button type="submit" class="btn btn-info" >
<span class="glyphicon glyphicon-tint"></span>  View
</button>
<br /> <span class="badge alert-info"> Find out what is currently in the database. </span><br />
</form>
<br />
<br />  

以下是我目前在select.php中所拥有的内容 -

<?php
/*** mysql hostname ***/
$hostname = '192.xx.xxx.xx';

/*** mysql username ***/
$username = 'Mitchyl';

/*** mysql password ***/
$password = 'root1323';

/*** database name ***/
$dbname = 'test';

try {
      $dbh = new PDO("mysql:host=$hostname;dbname=$dbname", $username, $password);
    /*** The SQL SELECT statement ***/
    $sql = "SELECT * FROM increment";

}
catch(PDOException $e)
    {
    echo $e->getMessage();
    }
?>

我只是不知道如何从SQL查询中获取数据并将其放在HTML表中。

任何建议都会很棒! 谢谢!

2 个答案:

答案 0 :(得分:3)

试试这个

<?php
  $hostname = '192.xx.xxx.xx';
  $username = 'Mitchyl';
  $password = 'root1323';
  $dbname = 'test';

  try {
    $dbh = new PDO("mysql:host=$hostname;dbname=$dbname", $username, $password);

    $sql = $dbh->prepare("SELECT * FROM increment");

    if($sql->execute()) {
       $sql->setFetchMode(PDO::FETCH_ASSOC);
    }
  }
  catch(Exception $error) {
      echo '<p>', $error->getMessage(), '</p>';
  }

?>

  <div id="content">

    <table>
      <?php while($row = $sql->fetch()) { ?>
      <tr>
        <td><?php echo $row['column1_name']; ?></td>
        <td><?php echo $row['column2_name']; ?></td>
        <td><?php echo $row['column3_name']; ?></td>

        ...etc...

      </tr>
      <?php } ?>
    </table>

   </div>

答案 1 :(得分:2)

假设您的sql返回一个名为$data的数组,其格式类似于$data = [['name' => 'name1'], ['name' => 'name2'], ...];

//First declare your data array
$data = [];

// Then execute the query
$result = $mysqli->query($sql)

// Then read the results and create your $data array
while($row = $result->fetch_array())
{
    $data[] = $row;
}

现在您已检查数据是否为空,然后使用foreach显示结果。

<?php if(empty($data)): ?>
    <h1>No results were found!</h1>
<?php else: ?>
    <h1><?= count($data) ?> results were found!</h1>
    <table class="table">
        <thead>
            <th>#</th>
            <th>Name</th>
        </thead>
        <tbody>
        <?php foreach ($data as $key => $value): ?>
            <tr>
                <td><?= ++$key ?></td>
                <td><?= $value['name'] ?></td>
            </tr>
        <?php endforeach; ?>
        </tbody>
    </table>
<?php endif; ?>

当然,除了bootstrap使用的默认类(.table)之外,您可以将您喜欢的任何类添加到表中。