繁体   English   中英

将文件数据保存在 mysql 数据库中 php

[英]save file data in mysql database in php

我有一个 csv 文件包含 118350 行,我想将每一行保存在我的数据库表中,我已读取数组中的整个文件并解析每一行以进行一些修改,我已经开始在我的数据库中保存文件内容,我有一个php 程序,但问题是它一次只保存 927 行,所以我必须一次又一次地运行我的 php 脚本以将更多数据保存在数据库中。

我的 php 代码是 ---

<?php
    $connection = mysql_connect('localhost', 'user', 'password') or die(mysql_error($connection));
    $select_db = mysql_select_db('dbname', $connection) or die(mysql_error($connection));

    $file = file('ip-to-country.csv');
    $data = str_replace("\"", "", $file, $j); //for removing ' " ' charactor from string
    $i = 0;
    for ($i = 0; $i < count($data); $i++) {
        $content = explode(',', $data[$i]);
        $ins = "insert into iplocation (startiprang,endiprang,concode,concode3,country) values ($content[0],$content[1],'$content[2]','$content[3]','$content[4]')";
        $result = mysql_query($ins, $connection);
    }
    echo "done";
?>

是否有任何 function 可以将所有文件数据无限制地存储在数组中。 我的文件大小约为 6 MB。 提前谢谢......我希望你明白我想要什么......提前谢谢。

如果您正在使用此 csv

http://ip-to-country.webhosting.info/node/view/6

你可以这样做:

create table iplocation (
id int not null auto_increment primary key,
startiprang int unsigned,
endiprang int unsigned,
concode varchar(50),
concode3 varchar(50),
country varchar(150)
) engine = myisam;

load data infile 'c:/ip-to-country.csv'
into table iplocation 
fields terminated by ',"'
(@startiprang,@endiprang,@concode,@concode3,@country)
set 
startiprang = replace(@startiprang,'"',''),
endiprang = replace(@endiprang,'"',''),
concode = replace(@concode,'"',''),
concode3 = replace(@concode3,'"',''),
country = replace(@country,'"','')

实际上这不是 PHP 问题。 可以使用 mySQL 中的LOAD DATA 命令轻松解决。 它看起来像:

LOAD DATA INFILE LOCAL '\var\tmp\test.csv' INTO TABLE sometable FIELD TERMINATED BY ';' LINES TERMINATED BY '\n' (column1, column2);

But if you really want to solve it with PHP then just create SQL file with INSERT commands in it for each CSV line and execute it with mySQL client.

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM