[英]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.