这段代码可以工作,但我想显示数据,但不使用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);
?>
3条答案
按热度按时间wrrgggsh1#
您必须使用string方法来输出打印或回音,以便将数据从数据库中获取到html。但是您可以用几种不同的方法将html从过程php中分离出来。
答。您可以使用jquery和xhr(ajax)从php中提取数据,并用jquery.html()、.clone()、.append()等填充空的html shell。。。
b。将数据库结果放入一个数组中,稍后可以在html中遍历该数组,如:
zzoitvuj2#
将业务逻辑与表示分离是symfony或laravel等框架所擅长的。
如果您不想使用其中一个框架,twig是php的一个模板引擎,这可能就是您想要的。
他们的文件很好。
https://twig.symfony.com/doc/2.x/intro.html
一个使用细枝的快速示例-更改路径以适合您的系统。这是假设一个linux环境。
首先,安装细枝。这将下载细枝目录调用供应商在您的主目录。对我来说
/home/john/vendor
```php composer require "twig/twig:^2.0"
twig
├── bootstrap.php
├── index.php
└── templates
└── index.php
iyfjxgzm3#
正如其他人所说,如果不使用一些模板引擎或框架,您将不得不使用echo或print之类的工具。
如果你想把它保存在一个文件中,这样把逻辑分开,其他的答案会对你有所帮助。
不过,也就是说,如果您希望将逻辑分为两个文件来进一步清理它,那么您可以这样做:
mysql.php文件
索引.php