I'm working on quite a large project in which there are a lot of places where code like the following exists:
function foo($a, $b, $c, $d, $e, $f) {
$clean = array();
$mysql = array();
$clean['a'] = htmlentities($a);
$clean['b'] = htmlentities($b);
$clean['c'] = htmlentities($c);
$clean['d'] = htmlentities($d);
//...
$mysql['a'] = mysql_real_escape_string($clean['a']);
$mysql['b'] = mysql_real_escape_string($clean['b']);
$mysql['c'] = mysql_real_escape_string($clean['c']);
$mysql['d'] = mysql_real_escape_string($clean['d']);
//...
//construct and execute an SQL query using the data in $mysql
$query = "INSERT INTO a_table
SET a='{$mysql['a']}',
b='{$mysql['b']}',
c='{$mysql['c']}',
d='{$mysql['d']}'";
}
Obviously this throws a lot of warnings in PHP for undefined indexes.
Is it really necessary to rewrite the code as follows?
function foo($a, $b, $c, $d, $e, $f) {
$clean = array();
$mysql = array();
$clean['a'] = htmlentities($a);
$clean['b'] = htmlentities($b);
$clean['c'] = htmlentities($c);
$clean['d'] = htmlentities($d);
//...
$mysql['a'] = (isset($clean['a'])) ? mysql_real_escape_string($clean['a']) : mysql_real_escape_string($a);
$mysql['b'] = (isset($clean['b'])) ? mysql_real_escape_string($clean['b']) : mysql_real_escape_string($b);
$mysql['c'] = (isset($clean['c'])) ? mysql_real_escape_string($clean['c']) : mysql_real_escape_string($c);
$mysql['d'] = (isset($clean['d'])) ? mysql_real_escape_string($clean['d']) : mysql_real_escape_string($d);
//...
//construct and execute an SQL query using the data in $mysql
if (isset($mysql['a']) and isset($mysql['b']) and isset($mysql['c']) and isset($mysql['d'])) {
$query = "INSERT INTO a_table
SET a='{$mysql['a']}',
b='{$mysql['b']}',
c='{$mysql['c']}',
d='{$mysql['d']}'";
}
}
You can simplify your function a lot if you use:
The isset() check at the showed position seems completely useless. The variables were already defined.