【问题标题】:How to show values from a MySQL database table inside HTML via PHP?如何通过 PHP 在 HTML 中显示 MySQL 数据库表中的值?
【发布时间】:2018-07-31 23:50:06
【问题描述】:

此代码有效,但我想显示数据但不使用回显,我想要包含 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);
?>

【问题讨论】:

  • 你为什么不想使用echo?它有什么问题?
  • @Lachie 因为我不想在后端写html,所以我想把逻辑放在后面,把html放在前面
  • 如果我理解正确的话,你需要 JS。

标签: php html mysql mysqli


【解决方案1】:

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

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

他们的文档非常好。

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

bootstrap.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);`

index.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

【讨论】:

  • 咦?!这和他们的问题有什么关系?
  • soviet 询问如何在不使用 echo 的情况下显示值,因为他们想将业务逻辑与前端分离。从数据库中获取结果并在我的编辑中在树枝模板中循环它们。这可以满足苏联的要求,将 html 和逻辑分开,并且不使用 echo。我认为这里不需要 JS。
  • 感谢约翰进行编辑。添加代码示例有助于支持您的答案,因为您的原始帖子仅包含一个链接。如果你看一下https://meta.stackexchange.com/questions/8231/are-answers-that-just-contain-links-elsewhere-really-good-answers,你就会明白他们为什么气馁。 只是想帮忙 :-)
  • 不,谢谢您的反馈。发布后,我意识到一个例子会更好。如果有一个如何安装、初始化和调用 twig 来呈现模板的示例,那就更好了。我会记住这一点。
【解决方案2】:

您将不得不使用字符串方法来输出您的printecho 以将肉从您的数据库获取到您的HTML。但是您当然可以通过几种不同的方式将您的 HTML 与过程式 PHP 分开。

A.您可以使用 jQuery 和 XHR (AJAX) 从 PHP 中提取数据并使用 jQuery .html()、.clone()、.append() 等填充空的 HTML shell...

B.您将数据库结果放入一个数组中,您可以稍后在 HTML 中遍历该数组,例如:

// backend code
while($row = $result->fetch()){
 $myData[] = $row; // makes a multi-dimensional array of your data
}

// then later in your HTML
<!DOCTYPE html>
...
<table>
 <tr>
  <th>id</th>
  <th>first_name</th>
  <th>last_name</th>
  <th>email</th>
 </tr>
<?php foreach($myData as $values){ ?>
 <tr>
  <td><?=$values['id'];?></td>
  <td><?=$values['first_name'];?></td>
  <td><?=$values['last_name'];?></td>
  <td><?=$values['email'];?></td>
 </tr>
<?php } ?>
</table>

【讨论】:

    【解决方案3】:

    正如其他人所说,如果不使用某些模板引擎或框架,您将不得不使用 echo 或 print。

    如果您想将其保存在一个文件中并以这种方式分离逻辑,那么其他答案将对您有所帮助。

    话虽如此,如果您希望将逻辑分成 2 个文件以进行更多清理,那么您可以这样做:

    mysql.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);
    
            // Close connection
            unset($pdo);
    
            if ($result->rowCount() > 0){
                return $result->fetchAll();
            } else{
                die("No records matching your query were found.");
            }
        } catch(PDOException $e){
            die("ERROR: Could not able to execute $sql. " . $e->getMessage());
        }
    
    ?>
    

    index.php

    <!DOCTYPE html>
    <html>
        <head>
            <title></title>
        </head>
        <body>
            <table>
                <thead>
                    <tr>
                        <th>id</th>
                        <th>first_name</th>
                        <th>last_name</th>
                        <th>email</th>
                    </tr>
                </thead>
                <tbody>
    
                <?php $rows = (include "mysql.php"); foreach ($rows as $row) { ?>
    
                    <tr>
                        <td><?= $row["id"] ?></td>
                        <td><?= $row["first_name"] ?></td>
                        <td><?= $row["last_name"] ?></td>
                        <td><?= $row["email"] ?></td>
                    </tr>
    
                <?php } ?>
    
                </tbody>
            </table>
        </body>
    </html>
    

    【讨论】:

      猜你喜欢
      • 2014-03-24
      • 2013-02-15
      • 1970-01-01
      • 1970-01-01
      • 2018-11-22
      • 1970-01-01
      • 1970-01-01
      • 2013-07-27
      相关资源
      最近更新 更多