php - Should I be returning DB results inside the function or loop through the results outside the function? -
so wondering what's best way/practise of querying database in function , printing results .php
page. got taught query in function()
, call function()
inside .php
page , loop through resultset inside .php
page.
here example of i'm doing - im wondering if "unsafe" or "not secure" or slower returning results in function? because @ moment - taking while load on page? because i'm doing using if statements inside while loop
?
showplaylist($statictestuser); if($numrecords == 0){ echo "<div class='no-found'>no playlists found</div>"; } else{ $htmloutput = "<div class='playlist-wrap'>"; $i = 1; while($arrrows = $stmt->fetch(pdo::fetch_assoc)){ $title = $arrrows['song-title'] $thumbnail=$arrrows['thumb'] $playtitle = $arrrows['playlistname']; $htmloutput .= "<div class='playlist-head'>"; //make sure title shown once - loop through rest. if($i == 1){ $htmloutput .= $playtitle; } $htmloutput .= "</div>"; $htmloutput .= "<div class='playlist-item'>"; $htmloutput .= "<div class='play-thumb'>".$thumbnail."</div>"; $htmloutput .= "<div class='play-title'>".substr($title, 0,30)."...</div>"; $htmloutput .= "</div>"; if($i == $numrecords){ $playid = $arrrows['pid']; $htmloutput .= "<div class='playlist-footer'>"; $htmloutput .= "<div class='play-stats'>"; $htmloutput .= "likes:".$arrrows['likes']." -- dislikes: ".$arrrows['dislikes']; $htmloutput .= "</div>"; $htmloutput .= "<div class='play-vote'>"; $htmloutput .= "<button name='playlike' type='submit' value='$playid'>like</button>"; $htmloutput .= "<button name='playdislike' type='submit' value='$playid'>dislike</button>"; $htmloutput .= "</div>"; $htmloutput .= "</div>"; } $i++; unset($playtitle); } $htmloutput .= "</div>"; echo $htmloutput; }
there aren't specific security issues code can see, best practice right use mvc - model, view, controller - design pattern. see here. or mvp - model, view, presenter - design pattern. see here. both similar.
using 1 of these patterns has many benefits biggest ones in opinion code readable, portability, , reusability. may speed things well.
the if statements inside code wouldn't whats slowing code down - repeated fetch @ beginning of while loop.
Comments
Post a Comment