由于项目需求同时不想直接用tp框架中的ORM而写的,对于运行在FPM模式下的php来说,采用ORM对web程序运行效率会产生显著的影响,一般情况下都是直接自己构建SQL语句以及建立表与表之间的关系。
这几个函数只针对一般情况,对于类型检查那一块,可以自己进行相应的扩展。
function checkDatabaseName( $name ) {
if(!is_string($name)) {
return false;
}
$bad_char_reg = "/(\.|\#|\~|\`|\$|\|\-|\)|\(|\=|\>|\<|\/)+/i";
$chinese_char_reg = "/[\x{4e00}-\x{9fa5}]+/ui";
$str = null;
if(!preg_match($bad_char_reg, $name)
||
(
!preg_match($chinese_char_reg, $name, $str)
&&
!empty($str)
)
) {
return false;
}
return true;
}
function getDataStructure( $table_name )
{
if ( !is_string($table_name) ) {
return null;
}
if( !class_exists('think\facade\Db') ) {
throw new \think\Exception('the Db driver was not loaded,please add it');
}
if( !checkDatabaseName($table_name) ) {
throw new \think\Exception('the table name is illegal name, please check it');
}
$data_structure = null;
try{
$data_structure = think\facade\Db::query('show full fields from '. $table_name);
} catch(\think\db\exception\DataNotFoundException $e) {
throw $e;
}
return $data_structure;
}
function checkpass($table_name, $table_col) {
$real_table_structure = getDataStructure( $table_name );
if( empty( $real_table_structure ) ) {
return false;
}
if(!is_array($table_col)) {
return false;
}
$data_fileds = array_column($real_table_structure, 'Type','Field');
foreach( $table_col as $field_name => $field_val ) {
if( isset($data_fileds[$field_name]) ) {
$type = strtok($data_fileds[$field_name], "(")[0];
$max_count = strtok($data_fileds[$field_name],"(")[1];
$max_count = (int) substr($max_count,0,strlen($max_count) - 1);
if($type == 'int'
|| $type == 'mediumint'
|| $type == 'bigint'
|| $type == 'tinyint'
|| $type == 'smallint'
) {
if(is_int($field_val) && strlen($field_val) <= $max_count) {
continue;
}
}
if($type == 'boolean') {
if((is_int($field_val) && strlen($field_val) == 1) || is_bool($field_val)) {
continue;
}
}
if($type == 'float'
|| $type == 'decimal'
|| $type == 'double'
|| $type == 'real'
) {
if(is_float($field_val)) {
continue;
}
}
if($type == 'char'
|| $type == 'varchar'
|| $type == 'tinytext'
|| $type == 'longtext'
|| $type == 'text'
) {
if(is_string($field_val) && strlen($field_val) <= $max_count) {
continue;
}
}
if(is_string($field_val) && strlen($field_val) <= $max_count) {
continue;
}
}
return false;
}
return true;
}