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

时间:2015-04-21 09:10:05

标签: php mysql

我有一个文本文件def.txt,它看起来像: -

输入已缓存的已用空闲共享缓冲区

记忆:4039 762 3277 0 59 251

我想以明智的方式阅读文件并将其插入mysql数据库中,如上所述。请帮我解决这个问题。

我目前的代码是: -

$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 个答案:

答案 0 :(得分:0)

看到你只使用第一行(是正确的行为?),这应该做。它需要数字并逐个插入。

$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/>";
    }
}

编辑:为安全性添加了mysqli_real_escape_string,虽然这些数字不应该那么重要。只是好习惯。