duaner1634 2015-10-05 14:37
浏览 61

使用PHP将TXT文件中的行插入SQL数据库

I have a file that contains data from a device, and I need to insert this data into a database. The text file looks like this:

10/01/15-20:37:30 = 40.2,25.4,42.3,54.3,70.0,66.6
10/01/15-20:38:26 = 67.3,18.4,30.6,39.3,70.0,66.6
10/01/15-20:39:21 = 74.5,16.8,28.2,36.0,70.0,66.6
10/01/15-20:40:16 = 76.8,16.6,27.6,35.2,70.0,66.6
10/01/15-20:41:12 = 78.1,16.4,27.3,34.9,70.0,66.6

And my code currently looks like this:

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


    // Create connection
    $conn = new mysqli($servername, $username, $password, $dbname);
    // Check connection
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    } 
?>

<?PHP

    $file_handle = fopen("datalog.txt", "r");

    while (!feof($file_handle) ) {

    $line_of_text = fgets($file_handle);
    $parts = explode('  ', $line_of_text);

    print $parts[0] . $parts[1]. "<BR>";

}

$datainsert = "INSERT INTO reading (val1, val2, val3, val4, val5, val6, val7, val8, val9, val10) VALUES ($parts[0])"; 

if (mysqli_query($conn, $datainsert)) {
    echo "New record created successfully";
} else {
    echo "Error: " . $datainsert . "<br>" . mysqli_error($conn);
}


?>

<?php
$conn->close();
?>

The error I get is this:

Error:

INSERT INTO reading (Box_ID, Time_Stamp, Temperature, Humidity, CO_Level, VOC_Reading_UOM, VOC_Reading_V1, VOC_Reading_V2, VOC_Reading_V3, VOC_Reading_V4) VALUES () Column count doesn't match value count at row 1

My database and site do connect without errors, and this page is the only one with problems. What is going wrong?

  • 写回答

2条回答 默认 最新

  • douzhi7661 2015-10-05 15:01
    关注

    You appear to be exploding by a string containing two spaces. In your text file, however, your 'fields' are separated by a single space. You should change your call to explode() to use a single space (or get fancy and look at preg_split()).

    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题