简体   繁体   中英

How to exclude HTML from PHP and PHP file still able to link with the HTML file?

View table <-- this is my example. And code is provided too. I need to separate HTML from PHP, moving HTML to another file but my PHP code still be able to link with it. Is there any idea? I am trying to make something like View model controller.

<html>
<head>
<meta charset="utf-8">
<title>View Records</title>
<link rel="stylesheet" href="css/style.css" />
</head>
<body>
<div class="form">
<p>
    <a href="dashboard.php">Dashboard</a> 
|   <a href="view.php">View Records</a> 
|   <a href="insert.php">Add Admin</a>
|   <a href="logout.php" onclick="return confirm('Are you sure to Logout?');">Logout</a>

</p>

<table width="100%" border="1" style="border-collapse:collapse;">
    <thead>
        <tr>
            <th><strong>ID</strong></th>
            <th><strong>Username</strong></th>
            <th><strong>User Password</strong></th>
            <th><strong>Full Name</strong></th>
            <th><strong>Edit</strong></th>
            <th><strong>Delete</strong></th>
        </tr>
    </thead>
</body>


<?php
$count=1;
$sel_query="Select * from admin ORDER BY id ASC;";
$result = mysqli_query($con,$sel_query);
while($row = mysqli_fetch_assoc($result)) { ?>


<tr>
    <td align="center"><?php echo $row["ID"]; ?></td>
    <td align="center"><?php echo $row["username"]; ?></td>
    <td align="center"><?php echo $row["user_pass"]; ?></td>
    <td align="center"><?php echo $row["fullname"]; ?></td>
    <td align="center">
        <a href="edit.php?id=<?php echo $row["ID"];?>">Edit</a></td>
    <td align="center">
        <a href="delete.php?id=<?php echo $row["ID"]; ?>"onclick="return confirm('Data cannot be retrieved after deleted. Are you sure to delete?');">Delete</a></td>


</tr>
<?php $count++; } ?>
</tbody>
</table>
</div>
</body>
</html>```

Separating the php and html is a good start, and helps you see the next step in converting to OOP and then MVC.

MVC at this point is too broad for a simple answer here, but I would recommend this as a first step as it has the underlying principles:

  1. PHP is always at the top; never output anything until all your logic is finished

  2. Load configuration

  3. Work with user input and redirect if POST

  4. Execute business logic

  5. Exit PHP and output HTML. Remember, PHP is essentially a templating language, might as well use it as such

Your code would then look something like this:


<?php

// load database connection, etc
$url = 'your url';

// deal with user input. Always use POST if data will be changed!
if($_POST['action'] == 'delete') {

  // delete from admin where id=?
  header('location: '.$url);
  die;
}

// end "controller" section
// begin "model" section

$sel_query="Select * from admin ORDER BY id ASC;";
$result = mysqli_query($con,$sel_query);

// end "model" section
// begin "view" section. 
// Note, you could simply put the html in a separate file and just include it here. 

?>
<html>
<head>
<meta charset="utf-8">
<title>View Records</title>
<link rel="stylesheet" href="css/style.css" />
</head>
<body>
<div class="form">
<p>
    <a href="dashboard.php">Dashboard</a> 
|   <a href="view.php">View Records</a> 
|   <a href="insert.php">Add Admin</a>
|   <a href="logout.php" onclick="return confirm('Are you sure to Logout?');">Logout</a>

</p>

<table width="100%" border="1" style="border-collapse:collapse;">
    <thead>
        <tr>
            <th><strong>ID</strong></th>
            <th><strong>Username</strong></th>
            <th><strong>User Password</strong></th>
            <th><strong>Full Name</strong></th>
            <th><strong>Edit</strong></th>
            <th><strong>Delete</strong></th>
        </tr>
    </thead>
    </tbody>
    <?php while($row = mysqli_fetch_assoc($result)): ?>

    <tr>
        <td align="center"><?= $row["ID"] ?></td>
        <td align="center"><?= $row["username"] ?></td>
        <td align="center"><?= $row["user_pass"] ?></td>
        <td align="center"><?= $row["fullname"] ?></td>
        <td align="center">
          <form method="post">
            <input type="hidden" name="action" value="delete" />
            <input type="hidden" name="id" value="<?= $row["ID"] ?>" />
            <input type="submit" value="Delete" />
          </form>
        </td>
      </tr>
      <?php endwhile; ?>
</tbody>
</table>
</div>
</body>
</html>

Notice that following this pattern is laying the groundwork for moving to mvc. But first, start working on your oop chops and move all the business logic into a model object.

After that, you can move the template to its own file, and have the model injected into the view, which lets the view have access to the info it needs, and then render the output.

Meanwhile, you'll need a router (all traffic is rerouted to index.php) and controller, and figure out which interpretation of MVC you will use;)

Here's a very basic solution.

Make an HTML file as a template. Eg "template.html". Use HTML comments as placeholders for the data. (I went with comments as it means the HTML remains compliant) I've left out some of the non-relevant bits, so hopefully you get the idea:

<html>
...
<table width="100%" border="1" style="border-collapse:collapse;">
<thead>
<tr>
    <th><strong>ID</strong></th>
    <th><strong>Username</strong></th>
    <th><strong>User Password</strong></th>
    <th><strong>Full Name</strong></th>
    <th><strong>Edit</strong></th>
    <th><strong>Delete</strong></th>
</tr>
</thead>
<tbody>
<!--ROW-->
<tr>
    <td align="center"><!--ID--></td>
    <td align="center"><!--username--></td>
    <td align="center"><!--user_pass--></td>
    <td align="center"><!--fullname--></td>
    <td align="center">
        <a href="edit.php?id=<!--ID-->">Edit</a></td>
    <td align="center">
        <a href="delete.php?id=<!--ID-->"onclick="return confirm('Data cannot be retrieved after deleted. Are you sure to delete?');">Delete</a></td>
</tr>
<!--ENDROW-->
</tbody>
</table>
</div>
</body>
</html>

Then, in your PHP code, you read in the html, find the row template, and replace the fields as needed:

<?php
// Read the template
$html = file_get_contents('template.html');

// Find the row template
$regRowTemplate = '/<!--ROW-->(.*)<!--ENDROW-->/i';
preg_match($regRowTemplate, $html, $m);
$rowTemplate = $m[1];

// Start building our replacement rows
$htmlRows = '';

$count=1;
$sel_query="Select * from admin ORDER BY id ASC;";
$result = mysqli_query($con,$sel_query);
while ($row = mysqli_fetch_assoc($result)) {
    // Start with a fresh copy of the template
    $htmlRow = $rowTemplate;
    // Replace comment placeholders with values
    foreach ($row as $key => $value) {
        $htmlRow .= str_replace('<!--' . $key . '-->', $value, $htmlRow);
    }
    // Append to our rows
    $htmlRows .= $htmlRow;
    $count++;
}
// Replace the row template with our expanded rows
$html = preg_replace(regRowTemplate, $htmlRows, $html);
// Do something with the html

Source untested, but should give you a good starting point. I kept it pretty raw. If I was doing this for real, I'd allow for the possibility of spaces in the comment placeholders by using a regular expression instead, but for now it's good enough.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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