我有一個包含來自設備的數據的文件,我需要將此數據插入到數據庫中。該文本文件是這樣的:使用PHP將TXT文件中的行插入到SQL數據庫中
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
而且我的代碼目前看起來是這樣的:
<?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();
?>
我得到的錯誤是這樣的:
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
我的數據庫和網站都連接不錯誤,而這個頁面是唯一有問題的頁面。出了什麼問題?
從查看該錯誤消息,您不會在SQL的VALUES部分添加任何內容。檢查'$ parts [0]'是否包含你認爲它包含的內容。 – andrewsi
錯誤消息表明它沒有在'VALUES()'中傳遞任何數據,所以查詢當然會失敗 – RiggsFolly
我將$ parts [0]放在值區域中,因爲我認爲這是代碼拉的地方來自的信息。如果您在代碼中看起來稍早,您將看到$ parts = explode,然後將值拉出並分開。所以我沒有正確地訪問這些信息就是你所說的? – graphicdesigner88