Data-driven PHP apps using MySQL often need to ascertain the type of a MySQL column value at runtime. Parsing table DDL may be overkill. Querying information_schema.columns can be slow. You might find some of these utilities from TheUsual useful. All except is_numeric_value() accept a PHP $colobj parameter of the sort returned by mysqli_fetch_field() ...
<?PHP
function has_charset( $colobj ) {
return $colobj->type>=252 && $colobj->type<=254 && $colobj->charsetnr<>63;
}
function is_binary( $colobj ) {
return $colobj->flags&128 && $colobj->charsetnr==63 && $colobj->type>=252 && $colobj->type<=254;
}
function is_boolean( $colobj ) {
return ( $colobj->type==1 || $colobj->type=="tinyint(1)" );
}
function is_date_or_time( $colobj ) {
return $colobj->type==7 || ($colobj->type>=10 && $colobj->type<=12);
}
function is_char( $colobj ) {
return ( $colobj->type == 253 || $colobj->type == 254 );
}
function is_date( $colobj ) {
return ( $colobj->type == 10 );
}
function is_blob( $colobj ) {
return ( isset( $colobj ) && $colobj->type >= 249 && $colobj->type <= 252 && $colobj->charsetnr == 63 );
}
function is_text( $colobj, $len=64 ) {
return ( $colobj->type >= 249 && $colobj->type <= 254 && char_length($colobj) > $len );
}
function is_numeric_value ( $value ) {
return preg_match( "/^[-,-.0-9]+$/", $value );
}
function is_numeric_type( $colobj ) {
return isset( $colobj ) && array_search( $colobj->type, array(0,1,2,3,4,5,8,9,16,246) ) !== FALSE;
}
?>
Last updated 18 Jun 2024 |
 |