我有一个包含1000个用户名的txt文件。它们由行分隔。(折线)。
我想将这些用户名导入到我的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文件,但不会将其保存在服务器上,它只会导入其中的内容。
寻求帮助,谢谢。
看一下这段代码,它应该可以实现您的目的:
<?php
$input_file = fopen("your_input_file.txt", "r") or die("Unable to open file!");
$output_file = fopen("your_output_file.txt", "w");
while(!feof($input_file)) {
$user = fgets($input_file);
$user = trim($user);
$query = "insert into table_name values ('" . $user . "');\n";
fwrite($output_file, $query);
echo $query;
}
fclose($input_file);
fclose($output_file);
?>
只需用输入和输出文件的文件名替换your_input_file和your_output_file。
一些其他信息:
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句