首页 > 解决方案 > 如何通过 PHP 在 HTML 中显示 MySQL 数据库表中的值?

问题描述

此代码有效,但我想显示数据但不使用回显,我想要包含 HTML 的 index.php 来显示它,我不想像下面的代码那样回显所有内容。这是PHP代码:

<?php
try{
$pdo = new PDO("mysql:host=localhost;dbname=demo", "root", "");
// Set the PDO error mode to exception
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    } catch(PDOException $e){
die("ERROR: Could not connect. " . $e->getMessage());
}

// Attempt select query execution
try{
$sql = "SELECT * FROM persons";
$result = $pdo->query($sql);
if($result->rowCount() > 0){
    echo "<table>";
        echo "<tr>";
            echo "<th>id</th>";
            echo "<th>first_name</th>";
            echo "<th>last_name</th>";
            echo "<th>email</th>";
        echo "</tr>";
    while($row = $result->fetch()){
        echo "<tr>";
            echo "<td>" . $row['id'] . "</td>";
            echo "<td>" . $row['first_name'] . "</td>";
            echo "<td>" . $row['last_name'] . "</td>";
            echo "<td>" . $row['email'] . "</td>";
        echo "</tr>";
    }
    echo "</table>";
    // Free result set
    unset($result);
} else{
    echo "No records matching your query were found.";
}
} catch(PDOException $e){
die("ERROR: Could not able to execute $sql. " . $e->getMessage());
}

// Close connection
unset($pdo);
?>

标签: phphtmlmysqlmysqli

解决方案


将业务逻辑与表示分离是 Symfony 或 Laravel 等框架做得非常好的事情。

如果您不想使用其中一个框架,Twig 是一个 PHP 模板引擎,它可能是您正在寻找的。

他们的文档非常好。

https://twig.symfony.com/doc/2.x/intro.html

使用 twig 的简单示例 - 更改路径以适合您的系统。这是假设一个linux环境。

首先,安装树枝。这会将树枝下载到您主目录中的目录调用供应商。就我而言/home/john/vendor

 php composer require "twig/twig:^2.0"

在 public_html 中创建以下内容

twig
├── bootstrap.php
├── index.php
└── templates
    └── index.php

引导程序.php

<?php
//load the autoloader from the vendor directory

require_once '/home/john/vendor/autoload.php';

//Tell twig where to look for the template files
$loader = new Twig_Loader_Filesystem('/home/john/public_html/twig/templates');

//load twig
$twig = new Twig_Environment($loader);`

索引.php

<?php
require_once 'bootstrap.php';
//Your database logic could go here

//Your results. Could be from a database, but I'm using a array for simplicity
$result_set = [
  [
    'id' => 1,
    'first_name' => 'Edmund',
    'last_name' => 'Blackadder',
    'email' => 'eblackadder@blackadder.com'
  ],
  [
    'id' => 2,
    'first_name' => 'Baldrick',
    'last_name' => 'Does he have one?',
    'email' => 'dogsbody@baldrick.com'
  ]
];

//Render the index.php template in the templates directory, assigning the $result_set to result_set
echo $twig->render('index.php', ['result_set' => $result_set]);

模板/index.php

<table>
  <tr>
    <th>id</th>
    <th>first_name</th>
    <th>last_name</th>
    <th>email</th>
  </tr>
{% for result in result_set %}
  <tr>
    <td> {{ result.id }} </td>
    <td> {{ result.first_name }} </td>
    <td> {{ result.last_name }} </td>
    <td> {{ result.email }} </td>
  </tr>
{% endfor %}
</table>

这既分离了后端/前端,又避免了使用 echo


推荐阅读