php读取txt文本在写入mysql数据库

php读取txt文本在写入mysql数据库,第1张

<php

/

以datatxt 为例

建义在数据存储到文本文档的时候

fputs("datatxt","$str1\t$str2\r\n");

以这样的形式!

/

$str = file_get_contents("datatxt") or die("文件打开失败");

$r = explode("\r\n",$str);

/

连接数据库

/

$sql = "insert into `表`('id','num') values ('"$r[0]"','"$r[1]"')";

mysql_query($sql);

//以上代码未进行测试,如有问题可问我

>

//第一种 

<php

$conn = mysql_connect("主机名","用户名","密码");

mysql_select_db("数据库名",$conn);

$sql = "select  from user";

$result = mysql_query($sql);

$data="";

while($row = mysql_fetch_row($result)){

    foreach($row as $v){

        $data =$v"|";      //加个树线隔开字段

    }

    nl2br($data);    //读完一行回车

}

file_put_contents("abctxt",$data);

//第二种

<php

$filename = "abctxt";

$res = fopen($filename,"r");

while(!feof($res)){

$buffer = fgets($res);

$buffer = str_replace(' ', '|', $buffer); 

$array = explode('|', $buffer); 

foreach($array as $v){

if(strlen($v)>0){

$arr[] = $v;

}

}

}

fclose($res);

//组装数组插入数据库就可以了

<php

$file_dir="1txt";

$fp=fopen($file_dir,"r");

$content=fread($fp,filesize($file_dir));//读文件

fclose($fp);

function replaces($str)//为各字段添加''

{

foreach($str as $k=>$v)

{

$str[$k]="'"trim($v)"'";

}

return $str;

}

function Get_item($tmp1,$tmp2,$cont,$sq)//取得sql语句;tmp1为记录分割点,tmp2为字段分割点

{

$tmp_rows=explode($tmp1,$cont);

foreach($tmp_rows as $key=>$value)

{

$tmp_rows2[$key]=replaces(explode($tmp2,trim($value)));

$sql[$key]=$sqimplode(",",$tmp_rows2[$key])")\"";

}

return $sql;

}

$sq="\"insert into table1 (a1,a2,a3) values (";//sql的前半部分,要完善!

$sql=array();

$sql=Get_item("-"," ",$content,$sq);

//$db=mysql_connect("localhost","root","abc");//联接mysql,自己加

//mysql_select_db(

foreach($sql as $v)

{

mysql_query($v);//执行sql;

}

//mysql_close($db);

>

或者生成一个1sql文件,再把它导入mysql;

这样写就不会错了,看看能否帮到你

<form id="form1" name="form1" method="post" action="" enctype="multipart/form-data">

<input type="file" name="textfield" id="textfield" />

<input type="submit" name="button" id="button" value="提交" />

</form>

<

if($_POST['button']!=""){

$url=$_FILES['textfield']['tmp_name'];//获取上传来的文件地址

$sql=file_get_contents($url);//打开文件

sql($sql);//执行读取函数

}

function sql($sql){

$conn=mysql_pconnect("localhost","root","123456");

mysql_select_db("shop",$conn);

mysql_query("set names utf8");

$R=mysql_query($sql);

while($v=mysql_fetch_array($R)){

echo $v['ai_id'];

echo "<hr>";

}

}

//sql($sql);

>

以上就是关于php读取txt文本在写入mysql数据库全部的内容,包括:php读取txt文本在写入mysql数据库、求PHP从数据库中读取内容并存入文件和从文件读取数据插入数据库的代码、php读取txt文件 然后写入数据库等相关内容解答,如果想了解更多相关内容,可以关注我们,你们的支持是我们更新的动力!

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/sjk/10197223.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-06
下一篇 2023-05-06

发表评论

登录后才能评论

评论列表(0条)

保存