Jacob Baytelman - Full stack developer, project manager, CTO

SQL Injections

You cannot fight SQL injections. Fighting them is too late. When it happens, your system is already damaged. So you'd better take precautions. Use the same approach as with condoms: think about protection BEFORE, not AFTER.

Inputs must be cleared always. And also checked for maximal length (depending on the db setup, values longer than your fields size can cause errors)

function ClearIt($input, $length){
// note, this function removes ' and ", 
//if you need them in your data, use mysqli_real_escape_string
	if (strlen($input)> $length) 
		$input = substr($input, 0, $length);
	$input= str_replace ("'", "", $input);		
	$input= str_replace ("\"", "", $input);
	return $input;

$input_param = ClearIt($_REQUEST['input_param'], 250); 

When it's possible, cast them to the needed type. E.g. you know for sure that input parameter "finished" can be either 1 or 0, so simply cast it to integer
	$finished = intval($_REQUEST['finished']);

If it's a kind of a status (and you cannot have it as integer), use exact comparison:
	$status = ClearIt($_REQUEST['status'], 50);
	if ($status=="DONE") {
		// do something
	elseif ($status=="PENDING") {
		// do something
	else {
		// do something
Thus you accept it only if it exactly matches your constants, otherwise you do nothing with them.

When possible, store data in the database in an encrypted / encoded format. It works if you do not need to 'like' search by these fields.

Protect the access to your server's file system. No matter how well your inputs are filtered, if hackers get access to your file system, they can modify your scripts or execute their own ones.

Always have backups. Even if an intruder drops your database, you will be able to recover.

Avoid unnecessary use of databases. For example, it's physically impossible to SQL inject this site, because it has no database behind them.

J.Baytelman March 25, 2016