2
我有一個包含1000個用戶名的txt文件。它們被線條分開。 (斷線)。將txt文件/數據導入我的mysql數據庫
我想導入這些用戶名到我的mysql表中。我已經嘗試了csv方法,但它不像上傳txt文件那麼簡單。因爲我需要將txt文件轉換爲csv文件,這是浪費時間。
CSV導入代碼:
mysql_connect('localhost', 'user', 'pass') or die(mysql_error());
mysql_select_db('db_name') or die(mysql_error());
$lines = file('import.txt');
$company_names = "";
$insert_string = "INSERT INTO `ImportedWordList`(`Word`) VALUES";
$counter = 0;
$maxsize = count($lines);
foreach($lines as $line => $company) {
$insert_string .= "('".$company."')";
$counter++;
if($counter < $maxsize){
$insert_string .= ",";
}//if
}//foreach
mysql_query($insert_string) or die(mysql_error());
我也試過一個方法,導入一個txt的數據,但txt文件必須在服務器上。這也浪費了我的時間,因爲如果我們在談論大文件。這是浪費時間&用法上傳這些文件到服務器,然後纔開始將它們上傳到數據庫。
代碼:
<?php
//connect to the database
$connect = mysql_connect("localhost","username","password");
mysql_select_db("mydatabase",$connect); //select the table
//
if ($_FILES[csv][size] > 0) {
//get the csv file
$file = $_FILES[csv][tmp_name];
$handle = fopen($file,"r");
//loop through the csv file and insert into database
do {
if ($data[0]) {
mysql_query("INSERT INTO contacts (contact_first, contact_last, contact_email) VALUES
(
'".addslashes($data[0])."',
'".addslashes($data[1])."',
'".addslashes($data[2])."'
)
");
}
} while ($data = fgetcsv($handle,1000,",","'"));
//
//redirect
header('Location: import.php?success=1'); die;
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Import a CSV File with PHP & MySQL</title>
</head>
<body>
<?php if (!empty($_GET[success])) { echo "<b>Your file has been imported.</b><br><br>"; } //generic success notice ?>
<form action="" method="post" enctype="multipart/form-data" name="form1" id="form1">
Choose your file: <br />
<input name="csv" type="file" id="csv" />
<input type="submit" name="Submit" value="Submit" />
</form>
</body>
</html>
我感興趣的導入TXT數據,也許用一個文本框,我會粘貼到它的用戶名,它會上傳或最好的辦法也許上傳的txt文件,但它不會保留在服務器上,它只會導入裏面的東西。
尋求幫助,謝謝。
您可以使用您喜歡的任何語言爲導入構建一個sql腳本,然後導入該腳本。 – dg131
這就是爲什麼我尋求幫助..我沒有設法做到這一點。 – BenTyler
沒問題。我已經發布了一個答案。看一看。 :) – dg131