So I am still somewhat new to PHP, MySQL, and Javascript but I have been working on a project so I have been learning fast. However, I feel like in my php pages I am mixing too much HTML and PHP. At first I thought it was standard practice but someone on SO informed me of how you should not mix the two and I began looking at my code.
For example, when loading a page of submissions I have a loop that looks something like this (condensed version):
<?php
while ($row = mysql_fetch_assoc($submissionQuery))
{
$submissionID = $row['id'];
?>
<div class="submission" id="submission<?php echo $submissionID; ?>">
<h3><?php echo $row['title']; ?></h3>
</div>
<?php } ?>
The reason why I don’t just enclose the entire block in PHP is because there is not only an h3 there and I don’t want to use mass-echo statements.
In my opinion this looks terrible and I’d like to know a better way of doing it. I suppose that I could store all the submissions in to an array and then loop through them later on but I see several downsides to this:
1) Unnecessarily storing values in to an array. Only going to recall them immediately after.
2) If there are a lot of submissions there may not be enough memory to store them.
3) Would require more code.
4) Would still have to loop through the array later on and in that case I am still mixing PHP and HTML (just to a lesser degree)
I don’t know. I just need some advice as to best handle this because I don’t want to do things the wrong way and then have to refactor everything later on when something breaks or gets too complex.
When working with PHP, it’s almost impossible to not mix PHP and HTML. But this doesn’t mean you’re mixing your presentation logic with your business logic. Those are two very distinct things.
In your example you’re mixing your code. A better way to do it would be to.
You have a file, call it submission_proccess.php, in that file you’d have this code.
Now
submission_view.phpis yourview, so to speak. There you would have something like thisThe important thing here is to see that you won’t have to touch your view file, if say you want to modify your query or maybe filter it. Your business logic is kept separate from how you show it. You can even remove the HTML include and just have a file that takes the
$submissionvariable and outputs it as JSON.Some things you should be looking at is