How to detect padding on an integer and treat it as a string?
I have this function to prepare variable to be used in a SQL query:
function sqlize($mInput)
{
if (!isset($mInput))
$mInput = "null";
elseif (strtolower($mInput) == "null") { }
elseif (is_numeric($mInput)) { }
elseif (is_string($mInput))
{
$mInput = trim($mInput);
$mInput = addslashes($mInput);
$mInput = '"' . $mInput . '"';
}
else
$mInput = "null";
return $mInput;
}
I have a string "0004", which is going in a "varchar field", is cought by is_numeric
, and is saved as "4" and not "0004". Is there a way to detect the padding and process it as a string?
Thank you!
EDIT
Correct answer based on Cesar and webbiedave tips:
function sqlize($mInp开发者_如何学Cut)
{
switch(TRUE)
{
default: break;
case (!isset($mInput)): $mInput = "null"; break;
case (strtolower($mInput) == "null"): break;
case (is_numeric($mInput)):
if ((string) intval($mInput) === (string) $mInput)
break;
case (is_string($mInput)):
$mInput = trim($mInput);
#v2
$mInput = $_SESSION['oCore']->oDatabase->sanatize($mInput);
// ADOdb's oDb->qstr();
# v1
#$mInput = addslashes($mInput);
#$mInput = '"' . $mInput . '"';
break;
}
return $mInput;
}
instead of is_numeric()
use (int)$var == $var
I saw a beautiful use of the switch, should be something like this:
function sqlize($mInput)
{
switch(TRUE)
{
default:
case (!isset($mInput)): $mInput = "null"; break;
case (strtolower($mInput) == "null"): break;
case (is_numeric($mInput)): break;
case (is_string($mInput)):
$mInput = trim($mInput);
$mInput = addslashes($mInput);
$mInput = '"' . $mInput . '"';
break;
}
return $mInput;
}
精彩评论