0

包含三个数据项集的文本文件被插入到 mysql 数据库表的三列中,这些数据项由 分隔,;被插入到单个列中。在SO上找到一段代码并根据要求对其进行了修改,但仍然无法按要求工作。知道有什么问题吗?谢谢!

数字.txt

one
two
three;
four
five
six;  
...

测试.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
---------------------
...  
4

1 回答 1

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)

只需指定您的表/列/文件名。

加载数据输入语法

于 2013-09-18T05:26:34.733 回答