如何在此代码中添加 nl2br 和 html实体


How do I add nl2br and htmlentities in this code

我需要一些帮助。如何将 nl2br() 和 htmlentities() 函数输出到我的代码中?两者都需要应用于"内容",而 htmlentity 需要应用于"标题"。

<?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';
}
?>

你可以为此使用一个新变量:

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>
        ";
    }
}

或者断开字符串:

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>
        ";
    }
}

最巧妙的方法是抽象获取过程,以便将数据需要分解的事实从绘制结果的视图过程中抽象出来。
添加一个函数:-

function demangle_row($row) {
  $row->content = nl2br($row->content);
  $row->content = htmlentities($row->content);
  $row->title   = htmlentities($row->title);
}

现在更改 while 语句,以使用上面的代码

While($row = $results->fetch_object()) {

成为

While($row = demangle_row($results->fetch_object())) {