[eluser]a&w[/eluser]
I had / have problems with CI double quoting a numeric value when running through db->escape().
From
system/database/DB_driver.php:
Code:
function escape($str)
{
switch (gettype($str))
{
case 'string' : $str = "'".$this->escape_str($str)."'";
break;
case 'boolean': $str = ($str === FALSE) ? 0 : 1;
break;
default: $str = ($str === NULL) ? 'NULL' : $str;
break;
}
return $str;
}
When I do something like escape("40"), the $str is recognized as a string so I end up with '"40"'.
Looking into the php manual I found:
Quote:Note: To test if a variable is a number or a numeric string (such as form input, which is always a string), you must use is_numeric().
and also:
Quote:Warning
Never use gettype() to test for a certain type, since the returned string may be subject to change in a future version. In addition, it is slow too, as it involves string comparison.
Instead, use the is_* functions.
To wit:
Code:
$type1 = gettype("40");//string
$type2 = is_numeric("40") ? 'numeric' : $type1;//numeric
$escapeVal1 = mysqli_real_escape_string($this->db->conn_id, $val);//"40"
$escapeVal2 = "'".$escapeVal1."'";//"'40'" .... over escaped
//my workaround:
$val = is_numeric("40") ? floatval($val) : $val;//40 .... so far so good
$val = $this->db->escape($val);//40 .... numeric value retained!
As a result, would something like this be better:
Code:
function escape($str)
{
if (is_numeric($str))
{
$str = $str;
}
elseif (is_null($str)
{
$str = 'NULL';
}
elseif (is_bool($str)
{
$str = ($str === FALSE) ? 0 : 1;
} else {
$str = "'".$this->escape_str($str)."'";
}
return $str;
}