I tried to import a csv file from another server using LOAD DATA LOCAL INFILE
but it gives me an error The user update failed: Can't find file
, even the file is exist in the path given. I also tried the LOAD DATA INFILE
but User access denied
Is there's any other way to import a csv file directly to the file path (without using any submit button) in the mysql database and delete the current data in the dbase table if there's a new csv file uploaded?
EDIT: I tried also this PHP script, to import the csv file without any button, but the csv file data is not importing
PHP (2nd code):
$mysqli = new mysqli("localhost", "user", "password", "dbasename");
$file = "/var/www/html/files/filename.csv";
$handle = fopen($file,'r');
while (($data = fgetcsv($handle, 10000, ",")) !== FALSE){
$num = count($data);
for ($c=0; $c < $num; $c++){
$col[$c] = $data[$c];
}
$col1 = $data[0];
$col2 = $data[1];
$col3 = $data[2];
$col4 = $data[3];
$col5 = $data[4];
// SQL Query to insert data into DataBase
$query = "INSERT INTO dbname.tablename(col1,col2,col3,col4,col5) VALUES('".$col1."','".$col2."','".$col3."','".$col4."','".$col5."')";
$mysqli->query($query);
}
fclose($handle);
Here's the PHP:
$sql = "LOAD DATA LOCAL INFILE 'filename.csv'
INTO TABLE dbname.tablename
FIELDS TERMINATED BY ','
OPTIONALLY ENCLOSED BY '\"'
LINES TERMINATED BY '\n'
IGNORE 1 LINES;";
$con=mysqli_connect("localhost","user","password","db");
// Check connection
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
};
$result = mysqli_query($con, $sql);
if (mysqli_affected_rows($con) == 1){
$message = "The data was successfully added!";
} else {
$message = "The user update failed: ";
$message .= mysqli_error($con);
};
echo $message;