Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

PHP

Rich Text Editor's and displaying its html tags and styles to the content on the webpage

Hello,

I have a rich text editor (ckeditor) and I don't know what code I need to use to preserve the html code that the rich text editor is creating. The only code that I have on the information going in to the database is a mysqli_real_escape_string(). So the information in the database has the the html tag in the database. My issue is that when I query the information on to the webpage, instead of doing the <p> tags, the <strong> tags, it displaying this

<p>Hello,</p>

<p><strong>asdfasdfsdfsafdsfdsadf</strong></p>

<p><img alt="smiley" src="http://www.bettergamerzunited.com/ckeditor/plugins/smiley/images/regular_smile.png" style="height:23px; width:23px" title="smiley" /></p>

I need this to display

Hello,

asdfasdfsdfsafdsfdsadf //<-- This bold

<img alt="smiley" src="http://www.bettergamerzunited.com/ckeditor/plugins/smiley/images/regular_smile.png" style="height:23px; width:23px" title="smiley" /> //<-- this image

The only thing that I have on the information coming out of the database is nl2br, and htmlspecialschars. What do I need to do to preserve the html tags, and it actually does the tags instead of echoing them.

How is this data getting into the database? A php file or sql file? Can we see that code?

Form with the rich text editor, and the php code that inputs in to the database..

include '../../core/init.php'; 
members_only();
include '../../includes/overall/header.php'; 

if(isset($_POST["post_type"])) {
    $post_type = $_POST['post_type'];
    $post_body = $_POST['post_body'];
    $post_body = mysqli_real_escape_string($mysqli, $post_body);
    $forum_section_id = (int)$_POST['fsID'];
    $forum_section_title = mysqli_real_escape_string($mysqli, $_POST['fsTitle']);
    $member_id = (int)$_POST['uid'];
    $post_author = $_POST['username'];
    $post_title = preg_replace('#[^A-Za-z0-9 ?!.,]#i', '', mysqli_real_escape_string($mysqli, $_POST['post_title']));

    if ($post_type == "a") {
        if ($post_title == "") {
            echo 'Your Title is missing';
        }
        if (strlen($post_title) < 10) {
            echo 'The Title needs to be at least 10 characters';
        }
        if (strlen($post_body) < 2) {
            echo 'Your body needs to be at lease 2 characters';
        }
        $sql = "INSERT INTO forum_post (post_author, post_author_id, date_time, type, section_title, section_id, thread_title, post_body) VALUES ('$post_author', '$member_id', CURRENT_TIMESTAMP, 'a', '$forum_section_title', '$forum_section_id', '$post_title', '$post_body')";
        $query = mysqli_query($mysqli, $sql) or die(mysqli_error($mysqli));
        $this_id = mysqli_insert_id($mysqli);
        $sql = "UPDATE forum_post SET otid = '$this_id' WHERE id = '$this_id'";
        $query = mysqli_query($mysqli, $sql) or die(mysqli_error($mysqli));
        echo "post_success";
        exit();
    }
}
if (isset($_GET['id']) && isset($_GET['title'])) {
    $section_id = $_GET['id'];
    $section_title = $_GET['title'];
} else {
    header('Location: message.php?msg=Stop messing with the urls');
}

<div class="container">
    <div class="panel panel-default">
        <!-- Default panel contents -->
        <div class="panel-heading">
            <h2><?php echo $section_title; ?>
            </h2>
        </div>
        <div class="panel-body">
            <div id="status"></div>
            <ol class="breadcrumb">
                <li><a href="/index.php">Home</a></li>
                <li><a href="/members/forums/">Forum Home</a></li>
                <li><a href="/members/forums/section.php?id=<?php echo $section_id; ?>"><?php echo $section_title; ?></a></li>
            </ol>

            <form id="postTread" onsubmit="return false" class="form-horizontal" role="form">
              <div class="form-group">
                <label for="topic_author" class="col-sm-2 control-label">Author</label>
                <div class="col-sm-10">
                  <input type="text" onfocus="emptyElement('status')" name="topic_author" class="form-control" id="topic_author" value="<?php echo $log_username; ?>" autocomplete="off" placeholder="" disabled>
                </div>
              </div>
              <div class="form-group">
                <label for="post_title" class="col-sm-2 control-label">Thread Title</label>
                <div class="col-sm-10">
                  <input type="text" onfocus="emptyElement('status')" name="post_title" class="form-control" id="post_title" value="" autocomplete="off" placeholder="Please type in the title for your thread">
                </div>
              </div>
              <div class="form-group">
                <label for="post_body" class="col-sm-2 control-label">Thread Body</label>
                <div class="col-sm-10">
                  <textarea type="text" onfocus="emptyElement('status')" name="post_body" class="form-control ckeditor" id="post_body" value="" autocomplete="off" placeholder="Please type in your body for your thread" rows="15"></textarea>
                </div>
              </div>
              <input id="fsID" type="hidden" name="fsID" value="<?php echo $section_id ?>">
              <input id="fsTitle" type="hidden" name="fsTitle" value="<?php echo $section_title; ?>">
              <input id="uid" type="hidden" name="uid" value="<?php echo $_SESSION['userid']; ?>">
              <input id="username" type="hidden" name="username" value="<?php echo $log_username; ?>">
              <input id="post_type" type="hidden" name="post_type" value="a">
              <button id="createbtn" onclick="newPost()" class="btn btn-primary col-sm-6">Create Thread </button>
            </form>
        </div>
    </div>
</div>

And the PHP code that is echoing the infromation out of the database

include '../../core/init.php'; 
members_only();
include '../../includes/overall/header.php'; 

$myAgoObject = new convertToAgo;

//Get the Id from the URL
$thread_id = (int)$_GET['id'];

//Checking to make sure the thread id exists
$query = mysqli_query($mysqli, "SELECT * FROM forum_post WHERE id = '$thread_id' AND type = 'a' LIMIT 1");
$numRows = mysqli_num_rows($query);

if ($numRows < 1) {
    $errors[] = 'That Thread does not exist. Stop playing with the URL\'s';
    exit();
} else {
    $sql = "UPDATE forum_post SET view_count = view_count + 1 WHERE id = $thread_id";
    $upcount = mysqli_query($mysqli, $sql);
}

//Setting all varibles
while ($row = mysqli_fetch_array($query)) {
    $post_author = $row['post_author'];
    $post_author_id = $row['post_author_id'];
    $date_time = $row['date_time'];
    $date_time = strftime('%b %d, %Y', strtotime($date_time));
    $section_title = $row['section_title'];
    $section_id = $row['section_id'];
    $thread_title = htmlspecialchars($row['thread_title'], ENT_QUOTES);
    $post_body = nl2br(htmlspecialchars($row['post_body'], ENT_QUOTES));
}

// now query an responses out of the database
$all_responses = '';
$query = mysqli_query($mysqli, "SELECT * FROM `forum_post` WHERE `otid` = '$thread_id' AND `type` = 'b'");
$numRows = mysqli_num_rows($query);
if($numRows < 1) {
    $all_responses = '<div class="alert alert-info text-center" role="alert">No one has respond to this post! You can be the first to post.<br></div>';
}else {
    while ($row = mysqli_fetch_array($query)) {
        $reply_author = $row['post_author'];
        $reply_author_id = $row['post_author_id'];
        $date_n_time = $row['date_time'];
        $converted_time = ($myAgoObject -> convert_datetime($date_n_time));
        $whenReply = ($myAgoObject -> makeAgo($converted_time));
        $reply_body = nl2br(htmlspecialchars(stripslashes($row['post_body'],ENT_QUOTES)));
        $avaquery = mysqli_query($mysqli, "SELECT * FROM users WHERE username = '$reply_author' AND activated = '1'");
        $userRow = mysqli_fetch_array($avaquery);
        $userLevel = $userRow["userlevel"];
        $signup = $userRow["signup"];
        $signup = strftime("%b %d, %Y", strtotime($signup));
        $lastLogin = $userRow["lastlogin"];
        $lastLogin = strftime("%b %d, %Y", strtotime($lastLogin));
        $avatar = $userRow["avatar"];
        $country = $userRow["country"];
        $post_author_avatar = '<img src="/user/' . $reply_author . '/' . $avatar . '" alt="' . $reply_author . '" class="user_pic">';
        if($avatar == NULL){
            $post_author_avatar = '<img src="/img/avatardefault.gif" alt="' . $reply_author . '" class="user_pic">';
        }
        $all_responses .= '<tr>';
        $all_responses .=   '<td class="td-user">';
        $all_responses .=       '<div class="forum-user-info">';
        $all_responses .=           '<a href="/' . $reply_author . '">' . $reply_author . '</a><br>' . $post_author_avatar . '<br>';
        $all_responses .=           'Access: ' . $userLevel . '<br>';
        $all_responses .=           'Joined: ' . $signup . '<br>';
        $all_responses .=           'Last Logged: ' . $lastLogin . '<br>';
        $all_responses .=       '</div>';
        $all_responses .=   '</td>';
        $all_responses .=   '<td class="td-reply">';
        $all_responses .=       '<div class="forum-reply">';
        $all_responses .=           $reply_body;
        $all_responses .=       '</div>';
        $all_responses .=       '<div class="forum-posted">';
        $all_responses .=           'Posted: ' . $whenReply;
        $all_responses .=       '</div>';
        $all_responses .=       '<div class="forum-reply-control clearfix">';
        $all_responses .=           'Like &bull; &nbsp;';
        $all_responses .=           'Edit &bull; &nbsp;';
        $all_responses .=           'Delete';
        $all_responses .=       '</div>';
        $all_responses .=   '</td>';
        $all_responses .= '</tr>';
    }
}

$editPostbtn = '<button class="btn btn-primary btn-lg" data-toggle="modal" data-target="#editPost">Edit</button>';

//This if statment is for the comments
if (isset($_POST['post_type'])) {
    $post_type = $_POST['post_type'];
    $post_body = $_POST['post_body'];
    //$post_body = $post_body, ENT_QUOTES);
    //$post_body = mysqli_real_escape_string($post_body);
    $forum_section_id = (int)$_POST['fsID'];
    $forum_section_title = htmlentities($_POST['fsTitle']);
    $member_id = (int)$_POST['uid'];
    $post_author = $_POST['username'];
    $thread_title = $_POST['thread_title'];
    $post_title = preg_replace('#[^A-Za-z0-9 ?!.,]#i', '',$_POST['post_title']);

    if ($post_type == "b") {

        $tid = (int)$_POST['tid'];

        if ($tid == "") {
            echo 'The Thread Id is missing';
            exit();
        }

        $sql = "INSERT INTO forum_post (post_author, post_author_id, otid, date_time, type, section_title, section_id, thread_title, post_body) VALUES ('$post_author', '$member_id', $tid , CURRENT_TIMESTAMP, 'b', '$forum_section_title', '$forum_section_id', '$post_title', '$post_body')";
        $query = mysqli_query($mysqli, $sql) or die(mysqli_error($mysqli));
        echo "reply_success";
    }
}

<div class="container">
    <div class="panel panel-default">
        <!-- Default panel contents -->
        <div class="panel-heading">
            <h2><?php   echo $thread_title . '<br><div class="forum-heading-created">Topic started by: <a href="/'. $post_author .'">' . $post_author . '</a> &nbsp; &bull; &nbsp; Created on: ' . $date_time . '</div>';   ?></h2>
            <?php 
            $userAndAdminControls = userAndAdminControls($post_author);
            if ($userAndAdminControls === true) {
                echo $editPostbtn;
            }
            ?>
        </div>
        <div class="panel-body">
            <?php 
            if (empty($errors) === false) {
                echo '<div class="alert alert-danger text-center"' . output_errors($errors) . '</div>';
            }
            ?>
            <ol class="breadcrumb">
                <li><a href="/index.php">Home</a></li>
                <li><a href="/members/forums/">Forum Home</a></li>
                <li><a href="/members/forums/section.php?id=<?php echo $section_id; ?>"><?php echo $section_title; ?></a></li>
            </ol>
            <?php echo $post_body; ?>
        </div>
        <!-- List group -->
        <table class="table">
            <?php echo $all_responses; ?>
        </table>
         <div class="panel panel-default">
            <div class="panel-body">
                <form id="postReply" onsubmit="return false" class="form-horizontal" role="form">
                  <div class="form-group">
                    <label for="post_body" class="col-sm-2 control-label">Please type in your response <?php echo $log_username; ?></label>
                    <div class="col-sm-10">
                      <textarea type="text" name="post_body" class="form-control" id="post_body" value="" autocomplete="off" placeholder="Please type in your body for your responce" rows="6"></textarea>
                    </div>
                  <input id="thread_title" type="hidden" name="thread_title" value="<?php echo $thread_title; ?>">
                  <input id="tid" type="hidden" name="tid" value="<?php echo $thread_id; ?>">
                  <input id="fsTitle" type="hidden" name="fsTitle" value="<?php echo $section_title; ?>">
                  <input id="fsID" type="hidden" name="fsID" value="<?php echo $section_id; ?>">
                  <input id="post_author" type="hidden" name="post_author" value="<?php echo $post_author; ?>">
                  <input id="post_author_id" type="hidden" name="post_author_id" value="<?php echo $post_author_id; ?>">
                  <input id="uid" type="hidden" name="uid" value="<?php echo $log_id; ?>">
                  <input id="username" type="hidden" name="username" value="<?php echo $log_username; ?>">
                  <input id="post_type" type="hidden" name="post_type" value="b">
                  <div id="status"></div>
                  <button id="forumComBtn" onclick="forumReply()" class="btn btn-primary login-submit-center">Post Reply </button>
                </form>
            </div>
        </div>
    </div>
</div>
<!-- Modal -->
<div class="modal fade" id="editPost" tabindex="-1" role="dialog" aria-labelledby="EditPost" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>
        <h4 class="modal-title" id="EditPost"><?php echo $thread_title . '<br><div class="forum-heading-created">Topic started by: <a href="/'. $post_author .'">' . $post_author . '</a> &nbsp; &bull; &nbsp; Created on: ' . $date_time . '</div>'; ?></h4>
      </div>
      <form id="editPost" onsubmit="return false" role="form">
          <div class="modal-body">
            <div class="form-group">
                <div id="editstatus"></div>
                <div class="edit_post">Please make your changes to you post <?php echo $log_username; ?></div><br>
                    <textarea type="text" name="editpost_body" class="form-control" id="editpost_body" value="" autocomplete="off"  rows="20"><?php echo strip_tags($post_body); ?></textarea>
                </div>
          </div>
          <div class="modal-footer">
            <input id="editpost_loguser" type="hidden" name="editpost_loguser" value="<?php echo $log_username; ?>">
            <input id="editpostthread_id" type="hidden" name="editpost_id" value="<?php echo $thread_id; ?>">
            <input id="editpost_author" type="hidden" name="editpost_author" value="<?php echo $post_author; ?>">
            <input id="editpost_type" type="hidden" name="editpost_type" value="a">
            <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
            <button id="editPostbtn" onclick="updatePostBody()" class="btn btn-primary">Save changes</button>
          </div>
       </form>
    </div>
  </div>
</div>

3 Answers

Here ya go.

echo htmlspecialchars_decode(stripslashes($row['']));

That didn't work, when I added the stripslashes it didn't display anything.

The code is above

If your talking about this line:

$reply_body = nl2br(htmlspecialchars(stripslashes($row['post_body'],ENT_QUOTES)));

then try changing it to:

$reply_body = nl2br(htmlspecialchars_decode(stripslashes($row['post_body'],ENT_QUOTES)));
htmlspecialchars_decode(stripslashes($row['post_body']), ENT_QUOTES);

That worked. Now how do I allow all special chars?

Hey everyone I've RTE, I've used it to send data into database, Now I want to edit the data by SQL update query , I want to render the data back into the editor . can anyone do this for me ?