繁体   English   中英

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

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

在上一个问题中 ,我询问了如何使用反引号为字段创建表。 现在,我们的团队决定在将某些.csv文件导入mysql时对其进行计算。 但是,我们的默认数据类型是VARCHAR(500) 我们的表具有一个Amount列,我们希望该数据类型为INT。 您能给我们一些提示吗? 谢谢。

这是我的代码:

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 / 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