dtah63820 2015-04-21 09:10
浏览 60

逐字阅读文本文件并相应地在mysql数据库中插入单词

i have a text file def.txt which looks like :-

Type total used free shared buffers cached

Mem: 4039 762 3277 0 59 251

i want to read the file word wise and insert these in mysql database as above format. please help me sort this out.

my current code is :-

$fh = fopen('F:\images\def.txt','r') or die($php_errormsg);

for($i=0;$i<=1;$i++)
 {
  if ($s = fgets($fh,1048576)) 
   {
    $words = preg_split('/\s+/',$s,-1,PREG_SPLIT_NO_EMPTY);
    $imp = implode(" ",$words);

    $con = mysqli_connect("localhost","root","root","test") or die("no connection".mysqli_connect_error());
    $a = "insert into test1 values('$imp')";
    if(mysqli_query($con,$a))
        {
            echo "done"."<br>";
        }
    else
        {
            echo "not done".mysqli_error($con)."<br>";
        }
    mysqli_close($con);

}
echo "<br>";
 }
 fclose($fh) or die($php_errormsg);
  • 写回答

1条回答 默认 最新

  • dtx63505 2015-04-21 21:12
    关注

    Seeing as you only use the first line (is that the correct behaviour?), this should do. It takes the numbers and inserts them one by one.

    $fh = fopen('F:\images\def.txt','r')
        or die('Could not open file');
    
    $con = mysqli_connect("localhost","root","root","test")
        or die("Could not access database. Error message: ".mysqli_connect_error());
    
    $matches = array();
    $line = fgets($fh);
    preg_match_all('/\b[0-9]+\b/',$line,$matches);
    
    foreach ( $matches as $word ) {
        $query = "insert into test1 (column_name) values('".
            mysqli_real_escape_string($con,$word)."')";
        if(mysqli_query($con,$query))
        {
            echo "Inserted $word<br/>";
        }
        else
        {
            echo "Failed to insert $word. Error message: ".mysqli_error($con)."<br/>";
        }
    }
    

    EDIT: Added mysqli_real_escape_string for security, although with these numbers it should not be that important. Just good practice.

    评论

报告相同问题?

悬赏问题

  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?
  • ¥100 求三轴之间相互配合画圆以及直线的算法
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 自己瞎改改,结果现在又运行不了了