如何在此代码中添加nl2br和htmlentities

时间:2016-07-12 15:46:16

标签: php mysql database

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

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

2 个答案:

答案 0 :(得分:0)

您可以使用新变量:

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

答案 1 :(得分:0)

最好的方法是抽象获取进程,以便数据需要进行解码,从抽取结果的视图进程中抽象出来。
添加功能: -

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())) {