As a newbie, my question is is it good practice to write code like this in PHP, mixing HTML and PHP or is there a better way of doing it
<?php
if (isset($_POST['submit']))
{
$principal_balance = $_POST['principal_amount'];
$interest_rate = $_POST['interest_rate'];
$repayment_amount = $_POST['repayment_amount'];
echo "<html>";
echo "<head>";
echo "<title> Loans </title>";
echo "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=iso-8859-1\" />";
echo" <link rel=\"stylesheet\" type=\"text/css\" href=\"styles/document.css\" />";
echo "<body>";
echo "<table>";
echo "<th> Principal Balance </th> <th> Interest Amount </th> <th> Principal Balance Amount Recovered </th> <th> Principal Balance </th> <th> Outstanding Balance </th>";
while ($principal_balance > 0)
{
if ($principal_balance < $repayment_amount)
{
exit;
}
else
{
$interest_amount = $interest_rate * $principal_balance * 1 / 12;
$principal_amount_recovered = $repayment_amount - $interest_amount;
$outstanding_balance = $principal_balance - $principal_amount_recovered;
round ($interest_amount, 2);
round ($principal_amount_recovered, 2);
round ($outstanding_balance, 2);
//echo $principal_balance . "," . $interest_amount . "," . $principal_amount_recovered . "," . $outstanding_balance . "<br />";
echo "<tr> <td>" . round ($principal_balance, 2) . "</td> <td>" . round ($interest_amount, 2) . "</td> <td>" . round ($principal_amount_recovered, 2). "</td> <td>" . round ($outstanding_balance, 2) . "</td> </td>";
$principal_balance = $outstanding_balance;
}
}
echo "</table>";
echo "</body>";
echo "</html>";
}
?>
Good question.
I always recommend people who have just started learning PHP that it isn’t very important for them to care about mixing markup and PHP script together, because at the beginning, what you need to learn is to get familiar with the syntax and see how PHP code works.
But when you improve to a further stage, it’s a GOOD practice to separate markup (HTML) from business layer (PHP script), so that your script looks cleaner, nicer and easier to maintain.
About you code above, I would recommend you to have a look at this topic, in my reply: How to connect controller to view in PHP OOP?