编辑 - 我更新了LogsModel.php以提供更好的图片。
我试图将数据插入到我的表中,其值为数组项,但数据将被插入两次。有谁知道为什么?当我运行脚本时,我的数据库插入了8行,但.txt文件中只有4行。
Access2.txt
2014-03-25 17:07:00.641
2014-03-25 17:07:00.641
2014-03-25 17:07:00.672
2014-03-25 17:07:00.672
LogsModel.php (更新)
function __construct($db) {
try {
$this->db = $db;
} catch (PDOException $e) {
exit('Database connection could not be established.');
}
}
public function getAllLogs()
{
$sql = "SELECT log_date, log_id, log_time FROM log_table";
$query = $this->db->prepare($sql);
$query->execute();
return $query->fetchAll();
}
public function insertFileContents()
{
$filename = 'C:/Program Files/FileMaker/FileMaker Server/Logs/Access2.txt';
// Open the file
$fp = @fopen($filename, 'r');
// Add each line to an array
if ($fp) {
$lines = explode("\n", fread($fp, filesize($filename)));
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();
}
}
}
LogsController.php
public function index()
{
// load a model, perform an action, pass the returned data to a variable
$logs_model = $this->loadModel('LogsModel');
$line_items = $logs_model->insertFileContents();
$logs = $logs_model->getAllLogs();
// load views.
require 'application/views/_templates/header.php';
require 'application/views/home/index.php';
require 'application/views/_templates/footer.php';
}
的index.php
<div class="container">
<table class="table table-striped">
<tr>
<td>Date</td>
<td>Time</td>
</tr>
<?php foreach ($logs as $log) { ?>
<tr>
<td><?php if (isset($log->log_date)) echo (string)$log->log_date; ?></td>
<td><?php if (isset($log->log_time)) echo (string)$log->log_time; ?></td>
</tr>
<?php } ?>
</table>
</div>
SQL
CREATE TABLE `log-data`.`log_table` (
`log_id` int(30) NOT NULL AUTO_INCREMENT,
`log_date` varchar(30) COLLATE utf8_unicode_ci NOT NULL,
`log_time` varchar(30) COLLATE utf8_unicode_ci NOT NULL,
PRIMARY KEY (`log_id`),
UNIQUE KEY `log_id` (`log_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
DB
1 2014-03-25 17:07:00.641
2 2014-03-25 17:07:00.641
3 2014-03-25 17:07:00.672
4 2014-03-25 17:07:00.672
5 2014-03-25 17:07:00.641
6 2014-03-25 17:07:00.641
7 2014-03-25 17:07:00.672
8 2014-03-25 17:07:00.672