du21064 2014-05-23 02:08
浏览 67
已采纳

php - 通过php数组插入多行到mysql中

I have a .txt file split into lines, and the items for each line are split into arrays log_dates and log_times. I'm trying to insert each log date and it's matching log time into my database which has log_date and log_time columns.

Access.txt

2014-03-16 13:57:35.089
2014-03-16 13:57:35.089
2014-03-16 13:57:35.089
2014-03-16 13:57:35.089  

LogsModel.php

function __construct($db) {
    try {
        $this->db = $db;
    } catch (PDOException $e) {
        exit('Database connection could not be established.');
    }
}

public function insertFileContents()
{
    $filename = 'C:/Program Files/FileMaker/FileMaker Server/Logs/Access.log';

    // Open the file
    $fp = @fopen($filename, 'r');

    // Add each line to an array
    if ($fp) {
        $lines = explode("
", fread($fp, filesize($filename)));

        foreach($lines as $line){
            $l = explode(" ", $line);
            $log_dates[] = $l[0];
            $log_times[] = $l[1];

            $sql = ("INSERT INTO log_table VALUES (log_date, log_time) VALUES ('$log_dates', '$log_times')");

            $query = $this->db->prepare($sql);
            $query->execute();
        }

        return true;
    }

}

Eventually I would like to have it so every time the page is accessed the database gets updated by the Access.txt file which will continue to accumulate new rows.

  • 写回答

1条回答 默认 最新

  • doutangshuan6473 2014-05-23 02:13
    关注

    $log_dates and $log_times shouldn't be arrays, they should be string variables:

        foreach($lines as $line){
            $l = explode(" ", $line);
            $log_dates = $l[0];
            $log_times = $l[1];
    
            $sql = ("INSERT INTO log_table (log_date, log_time) VALUES ('$log_dates', '$log_times')");
    
            $query = $this->db->prepare($sql);
            $query->execute();
        }
    

    You also had an extra VALUES keyword before the list of column names.

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

报告相同问题?

悬赏问题

  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥30 BC260Y用MQTT向阿里云发布主题消息一直错误
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)