将包含由;
分隔的三个数据项的集合的文本文件插入到一列中,该三个数据项将插入三列mysql数据库表中。在SO上找到一段代码并根据需要对其进行修改,但仍然无法按要求工作。知道什么可能是错的吗?谢谢!
num.txt
one
two
three;
four
five
six;
...
test.php的
<?php
$db = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$db) {
die('Could not connect: ' . mysql_error());
}
$filename = "num.txt";
$handle = fopen($filename, 'r');
$data = fread($handle, filesize($filename));
$rowsArr = explodeRows($data);
function explodeRows($data) {
$rowsArr = explode(";", $data);
return $rowsArr;
}
for($i=0;$i<count($rowsArr);$i++) {
$cols = explodeRows($rowsArr[$i]);
mysql_select_db("test", $db);
$query = sprintf('INSERT INTO voter (fname, lname, add) VALUES ("%s", "%s", "%s")', $cols[0], $cols[1], $cols[2]);
if (!mysql_query($query,$db))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
}
fclose($handle);
mysql_close($db);
?>
以上输出:
fname | lname | add
one | |
two | |
three | |
---------------------
four | |
five | |
six | |
---------------------
...
上述代码错误
Notice: Undefined offset: 1 in D:\xampp\htdocs\test.php on line 20
Notice: Undefined offset: 2 in D:\xampp\htdocs\test.php on line 20
1 record added
需要输出
fname |lname |add
one | two |three
---------------------
four | five |six
---------------------
...
答案 0 :(得分:0)
您可以使用简单的MySQL解决方法 -
LOAD DATA INFILE 'test.txt' INTO TABLE table1
FIELDS TERMINATED BY '\r\n'
LINES TERMINATED BY ';\r\n'
(column1, column2, @var)
SET column3 = TRIM(TRAILING ';' FROM @var)
只需指定您的表/列/文件名。