Jump to content

Which Way Is Better?


mds1256

Recommended Posts

Hi

 

I have read that you should keep the views away from the business logic so my question is which one of the below is better, the below are just examples but hopefully you can grasp what I am getting at.

 

keeping the php logic out of the html:

 

<?php


function displayRows()
{
$Con = mysqli_connect('localhost', 'usr', 'pass', 'db');

$query = mysqli_query($Con, "select id, name from table");

while($row = mysqli_fetch_object($query))
{
 echo "<a href=\"#\">".$row->name."</a>";
}
}
?>



<html>
<body>


<?php displayRows(); ?>



</body>
</html>

 

 

OR keeping the html out of the php function but putting some php into the body of the html

 

<?php


function displayRows()
{
$Con = mysqli_connect('localhost', 'usr', 'pass', 'db');

$query = mysqli_query($Con, "select id, name from table");

return $query;
}
?>



<html>
<body>


<?php


$myRes = displayRows();


while($row = mysqli_fetch_object($myRes))
{
echo "<a href=\"#\">".$row->name."</a>";
}


?>



</body>
</html>

Link to comment
https://forums.phpfreaks.com/topic/272350-which-way-is-better/
Share on other sites

Second because it has all the HTML being generated at once. If I read the first one I'd have to look up what displayRows() did just to know what the output HTML was (for starters).

 

Suggestion: make displayRows() return an array so the "view" doesn't have to know anything about the raw data source (a MySQL database accessed through mysqli).

Link to comment
https://forums.phpfreaks.com/topic/272350-which-way-is-better/#findComment-1401209
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.