dongmangwei3822 2017-07-04 17:12
浏览 145
已采纳

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

There is my database:

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

And there is my .txt file: (NULL, '1', 'text'),(NULL, '2', 'text'),(NULL, '3', 'text')...

Ok this works for me now:

    <?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;
?>

And now how do i upload multiple txt files, like from multiple folders, or just one folder?

  • 写回答

1条回答 默认 最新

  • dongshan8194 2017-07-04 17:17
    关注

    Try it like this:

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

    This goes only if your textfile has only this content you posted (NULL, '1', 'text'),(NULL, '2', 'text'),(NULL, '3', 'text').

    Take care for SQL injection.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 win from 窗口最大最小化,控件放大缩小,闪烁问题
  • ¥20 易康econgnition精度验证
  • ¥15 msix packaging tool打包问题
  • ¥28 微信小程序开发页面布局没问题,真机调试的时候页面布局就乱了
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致