0

我正在尝试读取一个文件,然后我试图插入到 mysql 表中我尝试了以下操作,我得到了 te 文本并显示了文件中的文本,但是当我尝试插入到 db 时,创建了行但是我没有任何帮助?

这是我的代码

<?php

$file_handle = fopen("text.htm", "r");
while (!feof($file_handle)) {
    $line = fgets($file_handle);
    echo $line;
    // make the DSN
    $dsn = 'mysql:host=localhost;dbname=text;';
    $user = 'text';
    $password = 'text';
    $name=$line;
}
try
{   
    $dbh = new PDO($dsn, $user, $password);
    // set the error mode to exception 
    $dbh->setAttribute(PDO::ATTR_ERRMODE, 
    PDO::ERRMODE_EXCEPTION);  
    $sql = 'INSERT INTO text (db_text) 
                   VALUES (:name)';
    $stmt = $dbh->prepare($sql);
    $stmt->bindParam(':name', $name);
    $stmt->execute();
}
catch (PDOException $e)
{
    echo 'PDO Exception Caught.  ';
    echo 'Error with the database: <br />';
    echo 'SQL Query: ', $sql;
    echo 'Error: ' . $e->getMessage();
}
fclose($file_handle);

?>
4

2 回答 2

1

我觉得你应该改变

$line = fgets($file_handle);

$line .= fgets($file_handle);

在while循环内。


另外,在while循环之前的某个地方$line实例化;$line = "";

fgets可能会false最后一次返回(或空行或其他内容)。

于 2012-11-28T17:10:39.177 回答
0

尝试在此之前声明 $name ......这可能是一个范围问题......

$name = "";    
$file_handle = fopen("text.htm", "r");
while (!feof($file_handle)) {
    $line = fgets($file_handle);
    echo $line;
    // make the DSN
    $dsn = 'mysql:host=localhost;dbname=text;';
    $user = 'text';
    $password = 'text';
    $name=$line;
}
于 2012-11-28T17:39:26.837 回答