简体   繁体   English

将CSV文件导入MySQL时,在创建表中更改数据类型-PHP

[英]Change datatype in creating table when importing csv files to MySQL - PHP

In my previous question , I asked how to create table using backticks for my fields. 在上一个问题中 ,我询问了如何使用反引号为字段创建表。 Now our team decided to have computations to some of our .csv files when importing it to mysql. 现在,我们的团队决定在将某些.csv文件导入mysql时对其进行计算。 However, our default datatype is VARCHAR(500) . 但是,我们的默认数据类型是VARCHAR(500) Our table has an Amount column and we like that datatype to be INT. 我们的表具有一个Amount列,我们希望该数据类型为INT。 Can you give us hints on how to do it? 您能给我们一些提示吗? Thank you. 谢谢。

Here's my code: 这是我的代码:

for($i=0;$i<count($data); $i++) {
    $f = strtolower(trim($data[$i]));
    if ($f) {
        // normalize the field name, strip to 20 chars if too long
        $f = substr(preg_replace ('/[^0-9a-z]/', '_', $f), 0, 100);
        $field_count++;
        $fields[] = $f.' VARCHAR(500)';
    }
}

$sqlcreate = "CREATE TABLE $table (" . implode(', ', $fields)  . ')';
echo $sqlcreate;

If you need to use a different column type based on the name of the column, you could use either an if/then or switch/case statement: 如果需要根据列名使用其他列类型,则可以使用if / then或switch / case语句:

for($i=0;$i<count($data); $i++) {
    $f = strtolower(trim($data[$i]));
    if ($f) {
        // normalize the field name, strip to 20 chars if too long
        $f = substr(preg_replace ('/[^0-9a-z]/', '_', $f), 0, 100);
        $field_count++;
        if($f == 'Amount') {
            $fields[] = $f.' INT(10)';
        } else {
            $fields[] = $f.' VARCHAR(500)';
        }
    }
}

$sqlcreate = "CREATE TABLE $table (" . implode(', ', $fields)  . ')';


echo $sqlcreate;

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

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