簡體   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