I’ve been using Dreamweaver’s GetSQLValueString function as part of my code for a long time. Over the last few projects, I’ve made some enhancements that you may find useful. It formats phones, SSN, does datetime (instead of just date) and of course you can add your own. Here it is, I hope you enjoy it.
function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") {
if (PHP_VERSION < 6) {
$theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;
}
$theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);
switch ($theType) {
case "text":
$theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
break;
case "long":
case "int":
$theValue = ($theValue != "") ? intval($theValue) : "NULL";
break;
case "double":
$theValue = ($theValue != "") ? doubleval($theValue) : "NULL";
break;
case "date":
$theValue = ($theValue != "") ? "'" . date("Y-m-d",strtotime($theValue)) . "'" : "NULL";
break;
case "datetime":
$theValue = ($theValue != "") ? "'" . date("Y-m-d H:i:s",strtotime($theValue)) . "'" : "NULL";
break;
case "displaydate":
$theValue = ($theValue != "") ? date("m/d/Y h:i:s A",strtotime($theValue)) : "NULL";
break;
case "ssn":
$theValue = ($theValue != "") ? "'" . substr($theValue,0,3)."-".substr($theValue,4,2)."-".substr($theValue,6,9) . "'" : "NULL";
break;
case "unssn":
$arrfind = array(" ","-","/","\");
$arrrepl = array("","","","");
$theValue = ($theValue != "") ? "'" . str_replace($arrfind,$arrrepl,$theValue) . "'" : "NULL";
break;
case "phone":
$phone = preg_replace("/[^0-9]/", "", $theValue);
if(strlen($phone) == 7)
return "'".preg_replace("/([0-9]{3})([0-9]{4})/", "$1-$2", $phone)."'";
elseif(strlen($phone) == 10)
return "'".preg_replace("/([0-9]{3})([0-9]{3})([0-9]{4})/", "($1) $2-$3", $phone)."'";
else
return "'".$phone."'";
break;
case "null":
$theValue = "NULL";
break;
case "defined":
$theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
break;
}
return $theValue;
}
Here is how you use it: Want a cleaned up phone number? Call it with this:
GetSQLValueString($yourval,"phone")
Need a good null?
GetSQLValueString("NULL","null")
How about a datetime?
GetSQLValueString($mydateval,"datetime")
You get it now, go on with your bad self.