Question

So I was just wondering if it was considered bad practice to open and close PHP statements, and let me explain what I mean. I know I can make variables at the beginning of my code but I like to group stuff together.I'm not sure if making one big PHP statement with all my variables is better / worse / same as opening and closing PHP statements similar to the example below.

<html>
<head></head> <---- HTML STUFF
<?php
(php stuff where connection to mysql db goes and other variables and errors)
?>
<body>
<html> <----- HTML stuff 
<?php
(php stuff to call a specific table from DB)
?>
<html> <----- HTML stuff 
<?php
(php stuff to call a specific table from DB)
?>
<html> <----- HTML stuff 
<?php
(php stuff to call a specific table from DB)
?>
</body>
<html> 

BTW the php variables I'm talking about are specific select statement from the DB.

ACTUAL CODE: or should select statements be at beg or sep file?

<table>
<tr>
<td align="left" width="200px">
Cover: Original Total
</td>
<td width="200px" align="center">
<?php
$original = "SELECT * FROM `comic_db`.`comic_db` WHERE comic_cover=\"original\"";
$orig_con = mysqli_query($comic_connect, $original);
$orig_total = mysqli_num_rows($orig_con);
echo $orig_total;
?>
</td>
</tr>
<tr>
<td width="200px" align="left">
Cover: Variants Total
</td>
<td width="200px" align="center">
<?php
$variants = "SELECT * FROM `comic_db`.`comic_db` WHERE comic_cover=\"variant\"";
$variant_con = mysqli_query($comic_connect, $variants);
$variant_total = mysqli_num_rows($variant_con);
echo $variant_total;
?>
</td>
</tr>
<tr>
<td align="left" width="200px">
Cover: Baby Totals
</td>
<td width="200px" align="center">
<?php
$baby = "SELECT * FROM `comic_db`.`comic_db` WHERE comic_cover=\"baby\"";
$baby_con = mysqli_query($comic_connect, $baby);
$baby_total = mysqli_num_rows($baby_con);
echo $baby_total;
?>
Was it helpful?

Solution

I'm assuming the repeated <html> tags in your example are just placeholders and would actually be <div>s and other elements making up the actual content of the page.

Your example is what's commonly called "spaghetti code" because it can quickly turn into an unmaintainable mess because you can't clearly see an overview of the HTML, nor can you see all the PHP code in one place.

The main thing to keep in mind is separating application logic (such as your database queries) from presentation (HTML and presentation logic like looping over an array to display it as an HTML list).

At the very least you'd want to put the main PHP code at the top of the file like you said, but it would be much better if it was in a separate file.

P.S. Any beginner book on PHP will discuss this in detail.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top