I have a box template for the products, so I've been practicing making one include
of that template inside a box While
like this:
$stmt->bind_result($product);
while ($stmt->fetch()) {
include 'template_box_product.php';
}
So to that template I already add the variables of the bind_result
:
<div class="item product">
<div class="thumbnail image">
<img src="default.jpg">
</div>
<div class="box">
<div class="heading">
<h3><?php echo $product; ?></h3>
</div>
<div class="author">
<span></span>
</div>
<div class="price">
<p><label>$300</label><em class="item-price">$120,00</em></p>
</div>
</div>
</div>
This worked without problems, but it is a good practice to do it this way, I mean in terms of execution time, performance, what other aspects should be evaluated to make decisions?
Or it should be used in the most usual/common way:
while ($stmt->fetch()) {
echo '<div class="item product">
<div class="thumbnail image">
<img src="default.jpg">
</div>
<div class="box">
<div class="heading">
<h3>'.$product.'</h3>
</div>
<div class="author">
<span></span>
</div>
<div class="price">
<p><label>$300</label><em class="item-price">$120,00</em></p>
</div>
</div>
</div>';
}
I suppose that the idea of having the content in a file and then including it is to have the code better organized and/or to be able to reuse code, which is a good practice.
One way to ensure content separation would be to put a
return
to the filetemplate_box_product.php
and then retrieve it into a variable once , then use that variable. This way you will avoid an include inside a loop, which is not a good idea, because after all it is boilerplate code.As for dynamic values, you can put markers and organize the output with
printf()
.So,
template_box_product.php
it would be like this:And, when you want to use it:
What will happen here is that the marker
%s
we put here:<h3>%s</h3>
will be replaced by the value of$producto
on each iteration. If you need more values, you put more markers and pass the respective values as parameters. Here its
means a marker for a string data type (string), and there are other types of markers depending on the data type, as you will see in the PHP Manual .