Monday, 30 September 2013

Inserting query results into a php string during foreach loop

Inserting query results into a php string during foreach loop

I have a php foreach loop listing news stories pulled from MySQL, as part
of the loop the story is printed out then underneath a query runs to pull,
then display any images attached to the story. This is the a simplifid
version of it:
foreach ($res AS $row) {
printf('<p>%s</p>' . PHP_EOL, nl2br($row['story']));
$qry3 = "select * from tpf_images where news_id=".$row['news_id'];
$res3 = $pdo->query($qry3);
foreach ($res3 AS $row3) {
printf('<a href="/images/%s%s.jpg" rel="lightbox[%s]" title="%s.
Photo Credit - %s" >
<img src="/images/%s%s-thumb.jpg" style="max-height: 250px;
max-width: 250px" alt="%s"/></a>' . PHP_EOL, $row3['url'],
$row3['alt'], $row['headline'], $str ,$row3['credit'],
$row3['url'], $row3['alt'], $row3['alt'] );
}
}
It works fine but means all images for a news story are under that story.
What I'm trying to achieve instead is that the images get printed out as
part of the story text, at the start of each paragraph. The story is
printed out with nl2br($row['story']), using nl2br a paragraph is achieved
with <br /><br />. So is there a way for php to scan nl2br($row['story'])
and if it finds <br /><br /> inserts the text I am using for the image
foreach:
printf('<a href="/images/%s%s.jpg" rel="lightbox[%s]" title="%s. Photo
Credit - %s" >
<img src="/images/%s%s-thumb.jpg" style="max-height: 250px; max-width:
250px" alt="%s"/></a>' . PHP_EOL, $row3['url'], $row3['alt'],
$row['headline'], $str ,$row3['credit'], $row3['url'], $row3['alt'],
$row3['alt'] );
That way the images will display in the body of the text rather thn under
it. If there are more images in the result than <br /><br /> the rest of
the images print out after the story like before.
Thanks for any help with this as I am completely stumped (also, was unsure
what the title should be so that can be edited to better suit if needed)

No comments:

Post a Comment