简体   繁体   English

比较MySQL和PHP之间的数据类型

[英]Comparing data types between MySQL and PHP

For example: I have variable $name and I like to save it to my database to table $table and column name. 例如:我有变量$ name,我想将其保存到数据库中以表$ table和列名。 But before I want to vefiry that it has the same data type as the database column (for varchar, char, text, ... it must be string). 但是在我想证明它具有与数据库列相同的数据类型之前(对于varchar,char,text,...它必须是字符串)。

How can I do this? 我怎样才能做到这一点?

To select MySQL data type: 选择MySQL数据类型:

$query = mysql_query("SELECT data_type
               FROM information_schema.columns
               WHERE table_schema = '".$dbName."'
               AND table_name = '".$table."'
               AND column_name = '".$column."' ");

Getting PHP type: 获取PHP类型:

 gettype($variable);

But how can I compare the data types (varchar, char, text to string)? 但是,如何比较数据类型(varchar,char,文本与字符串)?

Thank you very much! 非常感谢你!

This should be a simple problem to work around with a mapping array like the following sample code snippet: 要解决映射数组,例如下面的示例代码片段,这应该是一个简单的问题:

$type_map = array(
    'varchar' => 'string',
    'char' => 'string',
    'text' => 'string',
);

$column_type = 'text'; // get from DB query
$my_var = 'some string';
$var_type = gettype($my_var);

if(array_key_exists($column_type, $type_map) and
   $type_map[$column_type] == $var_type) {
    //proceed with insert of record
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM