繁体   English   中英

如何通过PHP在HTML内的MySQL数据库表中显示值?

[英]How to show values from a MySQL database table inside HTML via PHP?

这段代码有效,但我想显示数据但不使用echo,我希望index.php包含HTML来显示它,我不想像下面的代码那样回显所有内容。 这是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);
?>

将业务逻辑与演示文稿分开是Symfony或Laravel之类的框架做得很好的事情。

如果您不想使用其中一个框架,那么Twig是PHP的模板引擎,可能正是您想要的。

他们的文档非常好。

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

使用树枝的一个简单示例-更改路径以适合您的系统。 这是在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]);

template / 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>

这既分离了后端,又避免了使用回声

您将必须使用字符串方法来输出打印回显,以将数据从数据库获取到HTML。 但是您当然可以通过几种不同的方式将HTML与程序PHP分离。

答:您可以使用jQuery和XHR(AJAX)从PHP中提取数据,并使用jQuery .html()、. clone()、. append()等填充空HTML外壳。

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>

就像其他人所说的那样,如果不使用某些模板引擎或框架,则必须使用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>

暂无
暂无

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

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