0

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;
RAUSHAN KUMAR
  • 5,846
  • 4
  • 34
  • 70
Rukikun
  • 271
  • 3
  • 19

1 Answers1

1

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;
Sloan Thrasher
  • 4,953
  • 3
  • 22
  • 40