What you are trying to acheive is to prevent a form of XSS (Cross site scripting attacks) attacks. You are trying to prevent the persistent variety:
The persistent (or stored) XSS vulnerability is a more devastating
variant of a cross-site scripting flaw: it occurs when the data
provided by the attacker is saved by the server, and then permanently
displayed on "normal" pages returned to other users in the course of
regular browsing, without proper HTML escaping. A classic example of
this is with online message boards where users are allowed to post
HTML formatted messages for other users to read.
There are numerous options to prevent them. OWASP has a neat explanation.. Go through it and find out. But mostly its a very big problem for an Individual to handle solely.
The best way is to use HTMLPurifier which is both simple and easy. It may be a bit slow. But the extra processing is worth it. To give you an example of how simple it is to use here is a basic code:
<?php
require_once '/path/to/htmlpurifier/library/HTMLPurifier.auto.php';
$config = HTMLPurifier_Config::createDefault();
$purifier = new HTMLPurifier($config);
$clean_html = $purifier->purify($dirty_html);
?>
PS: HTMLPurifier has options to "whitelist". Use that for your advantage.
For example, you can fine tune allowed elements and attributes,
convert relative URLs to absolute ones, and even autoparagraph input
text! These are, respectively, %HTML.Allowed, %URI.MakeAbsolute and
%URI.Base, and %AutoFormat.AutoParagraph. The %Namespace.Directive
naming convention translates to:
$config->set('Namespace.Directive', $value);
E.g.
$config->set('HTML.Allowed', 'p,b,a[href],i');
$config->set('URI.Base', 'http://www.example.com');
$config->set('URI.MakeAbsolute', true);
$config->set('AutoFormat.AutoParagraph', true);
EDIT:
To answer your question on stopping malformed SQL Injection attacks refer to this question: How can I prevent SQL injection in PHP? and this answer
Quote:
Use prepared statements and parameterized queries. These are SQL statements that sent to and parsed by the database server separately from any parameters.
If you use PDO you can work with prepared statements like this:
$preparedStatement = $db->prepare('SELECT * FROM employees WHERE name = :name');
$preparedStatement->execute(array(':name' => $name));
$rows = $preparedStatement->fetchAll();
where $db is a PDO object, see the PDO documentation. The mysqli class also provides parameterized queries.