mds1256 Posted December 25, 2012 Share Posted December 25, 2012 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> Quote Link to comment https://forums.phpfreaks.com/topic/272350-which-way-is-better/ Share on other sites More sharing options...
requinix Posted December 25, 2012 Share Posted December 25, 2012 (edited) 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). Edited December 25, 2012 by requinix Quote Link to comment https://forums.phpfreaks.com/topic/272350-which-way-is-better/#findComment-1401209 Share on other sites More sharing options...
mds1256 Posted December 25, 2012 Author Share Posted December 25, 2012 Ok thank you I am trying to figure out the best way to return an array from a mysqli prepared statement. Quote Link to comment https://forums.phpfreaks.com/topic/272350-which-way-is-better/#findComment-1401220 Share on other sites More sharing options...
requinix Posted December 25, 2012 Share Posted December 25, 2012 If you have mysqlnd then there's a fetch_all() somewhere you can use. Otherwise just move that while loop you have someplace else, and instead of outputting $row stick it into an array. (Then return the array.) Quote Link to comment https://forums.phpfreaks.com/topic/272350-which-way-is-better/#findComment-1401243 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.