如何直接或通过php将txt导入mysql [英] how to import txt to mysql direct or through php

查看:53
本文介绍了如何直接或通过php将txt导入mysql的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将 .txt 导入到 MySQL `只有一个领域像这样我尝试了很多方法但是失败了:(

I need to import my .txt to MySQL ` which has only one field like this I have tries this many way but failed :(

能请你帮我吗如果有人对php有想法,那也是可以接受的.我为此花了两个,可惜没有成功:(

Could you help me please If any have idea with php that is also acceptable. I spend two for this unfortunately not succeeded yet :(

预先感谢

推荐答案

您可以使用Mysql LOAD DATA LOCAL INFILE 语法

You can use Mysql LOAD DATA LOCAL INFILE syntax

LOAD DATA LOCAL INFILE '/path/to/file.txt' 
    INTO TABLE 'table1'
    LINES TERMINATED BY '\n'

为此,请确保 Mysql 可以访问/path/to/file.txt .另外,执行查询的用户还必须具有 FILE 特权.

For this, make sure Mysql has access to /path/to/file.txt. Also the user who is executing the query must have FILE privilege.

使用纯PHP很容易.读取文件,构建查询,然后执行它.您需要构建查询,以免最终导致循环查询变慢.

With Pure PHP its easy. Read the file, build the query, execute it. You need to build the query so that you dont end up looping query which is slow.

$data = file("/path/to/file.txt", FILE_SKIP_EMPTY_LINES);

// make sure you have valid database connection prior to this point.
// otherwise mysql_real_escape_string won't work
$values = "('". implode("'), ('", array_map('mysql_real_escape_string', $data)). "')";

$query = "INSERT INTO `TABLE1` (`COLUMN1`) VALUES $values";

// Now just execute the query once.
mysql_query($query);

这篇关于如何直接或通过php将txt导入mysql的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆