我有一个代码,我从https://www.howtoforge.com/community/threads/importing-text-file-into-mysql.7925/获取并更改为我需要的代码,但是当我运行该程序时,它并没有将数据导入数据库
文字文件
GeoID|X|Y|Wood|Clay|Iron|Stone|Food|TerrainSpecificTypeID|TerrainCombatTypeID|RegionID
7025277|279|-1321|0|0|0|0|0|62|14|31
7025278|279|-1320|0|0|0|0|0|62|14|31
7025279|279|-1319|0|0|0|0|0|62|14|31
7025280|279|-1318|0|0|0|0|0|62|14|31
7025281|279|-1317|0|0|0|0|0|62|14|31
7025282|279|-1316|0|0|0|0|0|62|14|31
7025283|279|-1315|0|0|0|0|0|62|14|31
7025284|279|-1314|0|0|0|0|0|62|14|31
7025285|279|-1313|0|0|0|0|0|62|14|31
7025286|279|-1312|0|0|0|0|0|62|14|31
我目前正在使用的PHP代码
<?php
// Set Mysql Variables
$username = "root";
$auth = 'i-have-removed-it';
$db = mysql_connect("localhost", $username, $auth);
mysql_select_db("testdb",$db);
$file = "/tmp/map_datafile_test.txtt";
$fp = fopen($file, "r");
$data = fread($fp, filesize($file));
fclose($fp);
$output = str_replace("\t|\t", "|", $data);
$output = explode("\n", $output);
$language_id = "1";
$categories_id = 0;
foreach($output as $var) {
$categories_id = $categories_id + 1;
$tmp = explode("|", $var);
$GeoID = $tmp[0];
$X = $tmp[1];
$Y = $tmp[2];
$Wood = $tmp[3];
$Clay = $tmp[4];
$Iron = $tmp[5];
$Stone = $tmp[6];
$Food = $tmp[7];
$TerrainSpecificTypeID = $tmp[8];
$TerrainCombatTypeID = $tmp[9];
$RegionID = $tmp[10];
echo " categories_id: " . $categories_id . " Artikelgroep: " . $Artikelgroep . "<br>";
$sql = "INSERT INTO `World_Map`(`GeoID`, `X`, `Y`, `Wood`, `Clay`, `Iron`, `Stone`, `Food`, `TerrainSpecificTypeID`, `TerrainCombatTypeID`, `RegionID`) VALUES ('$GeoID','$X','$Y','$Wood','$Clay','$Iron','$Stone','$Food','$TerrainSpecificTypeID ','$TerrainCombatTypeID ','$RegionID')" or die("Insert failed: " . mysql_error());
mysql_query($sql);
}
echo "Done!";
?>
答案 0 :(得分:2)
你需要设置变量$ GeoID,$ X,$ Y,$ Wood,$ Clay,......
在foreach循环中,你得到文件的每一行,在$ tmp中你得到每一列。所以$ GeoID应该是$ tmp [0],$ X应该是$ tmp [1],依此类推。