shimmy shimmy - 4 months ago 19
SQL Question

How do I add nl2br and htmlentities in this code

I'm in need of some help. How can I output the nl2br() and htmlentities() functions into my code? Both need to be applied to 'content' but htmlentities to 'title'.

<?php
$sql = "
SELECT post.id AS postid, post.title AS title, post.created,
DATE_FORMAT(Created, '%d-%m-%Y') AS created,
post.content AS content, post.image AS image,
post.alttext AS alttext, blog.id, blog.blogname
FROM post
LEFT JOIN blog ON post.blogid = blog.id
WHERE blogid = \"" .(int)$_GET['id'] . "\"
ORDER BY postid DESC";

$results = $db->query($sql);

if($results->num_rows) {
while($row = $results->fetch_object()) {
echo "<hr>
<h3>{$row->title}</h3>
<p>{$row->created}</p>
<p>
<div id='blog-image'>
<img src='images/{$row->image}' alt='{$row->alttext}'>
</div>
{$row->content}
</p>";
}
} else {
echo 'No Results';
}
?>

Answer

You can use a new variable for that:

if ($results->num_rows) {
    while ($row = $results->fetch_object()) {
        $title = htmlentities($row->title);
        $content = nl2br(htmlentities($row->content));
        echo "<hr>
            <h3>{$title}</h3>
            <p>{$row->created}</p>
            <p>
                <div id='blog-image'>
                    <img src='images/{$row->image}' alt='{$row->alttext}'>
                </div>
                {$content}
            </p>
        ";
    }
}

Or break the string:

if ($results->num_rows) {
    while ($row = $results->fetch_object()) {
        echo "<hr>
            <h3>". htmlentities($row->title) ."</h3>
            <p>{$row->created}</p>
            <p>
                <div id='blog-image'>
                    <img src='images/{$row->image}' alt='{$row->alttext}'>
                </div>
                ". nl2br(htmlentities($row->content)) ."
            </p>
        ";
    }
}
Comments