ds20021205 2017-06-15 13:22
浏览 60
已采纳

将csv文件导入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. However, our default datatype is VARCHAR(500). Our table has an Amount column and we like that datatype to be 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;
  • 写回答

1条回答 默认 最新

  • duannan3959 2017-06-15 13:34
    关注

    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:

    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;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 TMC2209串口模式下读取不到寄存器的值串口助手蓝色字体是发过去的消息,绿色字体是收到的消息,第二行发送读取寄存器的指令但是没有读取到寄存器的值串口助手如下图:接线如下图,如何解决?
  • ¥15 高通安卓11提取完整线刷包软件,或者优博讯dt50顺丰刷机包
  • ¥20 C,有个译码器,换了信道就跑不出原来数据
  • ¥15 MIMIC数据库安装问题
  • ¥60 基于JTag协议开发Fpga下载器上位机,哪位大🐂有偿指导?
  • ¥20 全书网Java爬取数据
  • ¥15 怎么获取红包封面的原始链接,并且获取红包封面序列号
  • ¥100 微信小程序跑脚本授权的问题
  • ¥100 房产抖音小程序苹果搜不到安卓可以付费悬赏
  • ¥15 STM32串口接收问题