Save HTML Content into Database

    Generally we have required to save HTML Content i.e. a HTML page or a Block of content into Database. But if we Directly save it to Database, Its throw error due to Special Character and Quotation in the Content.

    So First we have to Convert it to database supported Value. We can do it by Decoding the html.
In PHP we have a Function "htmlspecialchars" and for Decoding the Function is "htmlspecialchars_decode".

So Here is the Code:

  • Create a Form into a File i.e. "form.php".
  • In this Example, we will get only one input on textarea.
  • Code will be as Follow:
########################
Code for form.php
########################
<html>
<head>
<title>
Form For HTML Element Save into Database.
</title>
</head>

<body>

<div style="width:250px;margin:0px auto;background:#666666;padding: 20px;">

<h4>
Save HTML Content into Database
</h4>

<form action="saveform.php" method="POST">
<textarea name="content" placeholder="Please Input your HTML here" style="min-height:200px; width:100%;"></textarea>
<br/>
<input type="submit" name="submit" value="Save Data Into Database" style="width:100%;" />
</form>
</div>

</body>
</html>
########################

  • Now Crate a Table into Database.
  • Use this Command: " CREATE TABLE `test`.`htmlcontent` ( `id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY , `content` TEXT NOT NULL , `timeinserted` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ) ENGINE = INNODB; "
  • Now Create a File "saveform.php"
  • Code will be as Follow:
########################
Code for form.php
########################
<?php
if(isset($_POST['content']))  // for checking value is posted from the form.php
{
$content = $_POST['content']; // Get POST value into a variable
echo "<br/>Posted Data is:<br/>";
echo $content;
echo "<hr/><br/>Encoded Data is:<br/><hr/>";
echo $content = htmlspecialchars($content);
echo "<hr/><br/> Decoded Data is:<br/><hr/>";
echo $content = htmlspecialchars_decode($content);
} else {
echo "Nothing has been Posted.";
}
?>
  

Comments

Popular posts from this blog

Page Unload Show Notification to user

Function Oriented File Upload PHP

Upload File Using PHP - Example For Image