在web设计中插入PHP代码,无需大量代码。解决了的
我对PHP/SQL相当陌生,我已经轻松地使用它一年左右了,我决定开始更多地使用它 我想第一个问题是,在网页设计中插入。有没有办法把它放在一个地方,这样我就不会把代码块放进一行代码中,更像是一个include?我希望它不会在my home.php中编码管理员用户数据库表。我可能会问一些非常简单的问题,我只是不喜欢在我的代码中包含以下内容,而且很难找到东西在web设计中插入PHP代码,无需大量代码。解决了的,php,sql,Php,Sql,我对PHP/SQL相当陌生,我已经轻松地使用它一年左右了,我决定开始更多地使用它 我想第一个问题是,在网页设计中插入。有没有办法把它放在一个地方,这样我就不会把代码块放进一行代码中,更像是一个include?我希望它不会在my home.php中编码管理员用户数据库表。我可能会问一些非常简单的问题,我只是不喜欢在我的代码中包含以下内容,而且很难找到东西 <div class="w3-card w3-col s3 w3-light-grey w3-border w3-padding">
<div class="w3-card w3-col s3 w3-light-grey w3-border w3-padding">
<h4 class="w3-center w3-teal">User Database</h4>
<table class="w3-table-all">
<th>Name</th>
<th>Email</th>
<th>Status</th>
<?php
$conn = mysqli_connect("localhost", "root", "", "registration");
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT username, email, user_type FROM users";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr><td>" . $row["username"] . "</td><td>"
. $row["email"]. "</td><td>" . $row['user_type'] . "</td></tr>";
}
echo "</table>";
} else { echo "0 results"; }
$conn->close();
?>
</table>
</div>
用户数据库
名称
电子邮件
地位
最简单的解决方案是将PHP代码移动到另一个文件,比如“helper\u functions.PHP”。所以结果会是这样的:
helpers.php
<?php
function print_rows(){
// Your code goes here
}
?>
helpers.php
在视图文件中,只需包含helpers文件并调用函数,如下所示:
<div class="w3-card w3-col s3 w3-light-grey w3-border w3-padding">
<h4 class="w3-center w3-teal">User Database</h4>
<table class="w3-table-all">
<th>Name</th>
<th>Email</th>
<th>Status</th>
<?php
require_once("helper_functions.php");
print_rows();
?>
</table>
</div>
用户数据库
名称
电子邮件
地位
这决不是最好的解决办法。如果您想编写更干净、分离和组织的代码,我建议您阅读有关MVC体系结构的内容 ——这就是你要找的。