Php- How to build a safe SQL and script injection string

One important question for php web developers is how to build a string which is safe in every aspects. The strings come from users inputs by Post and Get requests must get verified first before going ahead with them and using them in SQL aueries for mySQL or mySQLi. Here is function that helps you to check your strings safety.

function safestr($str){
	global $db_con;   // Replace it with your database link or connection.
	$result		= mysqli_real_escape_string($db_con,htmlspecialchars($str));
	return $result;


Note that in this code you need to replace the $db_con variable with your own variable who makes connection to the database. Another point here is that this function is written for mySQLi. if you use mySQL, remove ‘i’ from ‘mysqli_real_escape_string’.
The performance of this function is to check the special HTML characters (like < or >) first and then check for SQL injection by quotes.
Hope to be useful!

Be the first to comment

Leave a Reply

Your email address will not be published.