我知道有很多与此相关的问题,但我似乎无法找到解决我的错误的方法。
我的CSV:
我的SQL表:
我想在MYSQL中插入CSV。
据我所知,我不需要为此编写代码,我希望数据在MYSQL中,因为python代码每1小时检索一次代码刷新。
以下是我的代码:
首先尝试:
<?php
//database connection details
$connect = mysql_connect('127.0.0.1','admin','password');
if (!$connect) {
die('Could not connect to MySQL: ' . mysql_error());
}
//your database name
$cid =mysql_select_db('weather',$connect);
// path where your CSV file is located
define('CSV_PATH','C:/scripts/');
// Name of your CSV file
$csv_file = CSV_PATH . "nea.csv";
if (($handle = fopen($csv_file, "r")) !== FALSE) {
fgetcsv($handle);
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$num = count($data);
for ($c=0; $c < $num; $c++) {
$col[$c] = $data[$c];
}
// column name in mysql = column in csv?
$validTime = $col[0];
$Date = $col[1];
$Time = $col[2];
$Lat = $col[3];
$Lon = $col[4];
$AreaName = $col[5];
// SQL Query to insert data into DataBase
$query = "INSERT INTO neaweather(validTime, Date, Time, Lat, Lon, AreaName)
VALUES('".$col[0]."','".$col[1]."','".$col[2]."','".$col[3]."','".$col[4]."','".$col[5]."')";
$s = mysql_query($query, $connect );
}
fclose($handle);
}
echo "File data successfully imported to database!!";
mysql_close($connect);
?>
第二次尝试:
<?php
//set the connection variables
$hostname = "127.0.0.1";
$username = "admin";
$password = "password";
$database = "weather";
$filename = "C:/scripts/nea.csv";
//connect to mysql database
$connection = mysqli_connect($hostname, $username, $password, $database) or
die("Error " . mysqli_error($myConnection));
// open the csv file
$fp = fopen($filename,"r");
//parse the csv file row by row
while(($row = fgetcsv($fp,"500",",")) != FALSE)
{
$sql = "INSERT INTO neaweather (ValidTime, Date, Time, Lat, Lon, AreaName) VALUES ( '".mysqli_escape_string($data[0])."','".mysqli_escape_string($data[1])."','".mysqli_escape_string($data[2])."','".mysqli_escape_string($data[3])."','".mysqli_escape_string($data[4])."','".mysqli_escape_string($data[5])."')";
mysqli_query($myConnection,$sql);
if($query){
echo "row inserted\n";
}
else{
echo die(mysqli_error());
}
}
fclose($fp);
//close the db connection
mysqli_close($myConnection);
?>
编辑:我运行了两个代码,根本没有错误。但是,数据仍然没有进入MYSQL