I have looped through the $elements 6 times to create 6 identical containers for each service a company offers. I'm trying to put the "if while" loop at the bottom of the php inside the $element4 'overlay' div. The "if while" loop calls the service title from the MySQL database and displays it on the webpage. I have tried pasting the php code directly between the div tags, I have tried leaving it where it is, I have tried putting the "if while" loop in its own file and putting the include statement between the 'overlay' div tags. Nothing is working. With previous attempts, I have been able to get the h3 tags to populate in the wrong spots in the DOM, but I can't get them where I want them for some reason. Can you please tell me how I can get the output of the "if while" loop to display in the "overlay" div?`
$element = "<div class='service'>";
$element2= "<div class='img_container'>";
$element3= "<img class='service_img'/></div>";
$element4= "<div class='overlay'></div>";
$element5= "<div class='service_details'></div></div>";
$count = 6;
foreach( range(1,$count) as $item){
echo $element, $element2, $element3, $element4, $element5;
}
?>
<?php
if($resultCheck > 0){
while($row = $result->fetch_assoc()){
echo "<h3 class='service_title'>" . $row['service_title'] . "<br>" . "</h3>";
}}
?>
CodePudding user response:
See Refactored Further Below
To include that foreach loop on EACH service, you could adjust your code to look something like this:
<?php
$element = "<div class='service'>";
$element2 = "<div class='img_container'>";
$element3 = "<img class='service_img'/></div>";
$element4 = "<div class='overlay'></div>";
$element5 = "<div class='service_details'></div></div>";
$count = 6;
// this will end up with the title BEFORE the service element
// <h3 >...</h3>
// <div >...</div>
?>
<div >
<?php if ($resultCheck > 0) {
while ($row = $result->fetch_assoc()) {
echo "<h3 class='service_title'>" . $row['service_title'] . "<br>" . "</h3>";
// the below loop is going to create 5 `<div >...</div>`
// for EACH $row
foreach (range(1, $count) as $item) {
echo $element, $element2, $element3, $element4, $element5;
}
// you may want to instead want to echo directly
// echo $element, $element2, $element3, $element4, $element5;
}
} ?>
</div>
<?php
// ... rest of code
Refactored
From reading you description, I think what you're after is something more like this:
<?php
// refactored
// this format will include the title INSIDE the service element
// <div >
// <h3 >...</h3>
// ...
// </div>
?>
<div >
<?php if ($resultCheck > 0) {
while ($row = $result->fetch_assoc()) { ?>
<div >
<h3 ><?php echo $row["service_title"]; ?></h3>
<div >
<img />
</div>
<div ></div>
<div ></div>
</div>
<?php }
} ?>
</div>
<?php
// ... rest of code