如何将.txt文件上传到数据库?

时间:2017-07-04 17:12:43

标签: php mysql

有我的数据库:

CREATE TABLE Persons (
ID int AUTO_INCREMENT,
Father varchar(255) NOT NULL,
Text varchar(255),
PRIMARY KEY (ID));

还有我的.txt文件: (NULL,' 1',' text'),(NULL,' 2',' text'),(NULL,') ; 3','文字')...

好的,现在对我有用了:

    <?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "mydb";

try {
    $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    // set the PDO error mode to exception
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$text_file = file_get_contents('newfile.txt');
    $sql = "INSERT INTO `Persons` (`ID`, `Father`, `Text`) VALUES".$text_file;
    // use exec() because no results are returned
    $conn->exec($sql);
    echo "New record created successfully";
    }
catch(PDOException $e)
    {
    echo $sql . "<br>" . $e->getMessage();
    }

$conn = null;
?>

现在我如何上传多个txt文件,例如从多个文件夹或只是一个文件夹?

1 个答案:

答案 0 :(得分:0)

试试这样:

$text_file = file_get_contents('myTextFile.txt');
$sql = "INSERT INTO Persons (ID,Father,Text)VALUES".$text_file;

仅当您的文本文件您发布的(NULL, '1', 'text'),(NULL, '2', 'text'),(NULL, '3', 'text')内容时,才会这样做。

注意SQL注入。