-2

Can someone please help me to make this script check if the file exists, before it truncate the table. If filename not exists, I want to stop the import.

<?php
//set the connection variables
$hostname = "host";
$username = "username";
$password = "pass";
$database = "database";
$filename = "filename.csv";

//connect to mysql database
$connection = mysqli_connect($hostname, $username, $password, $database) or die("Error " . mysqli_error($connection));

mysqli_query($connection, "TRUNCATE TABLE `my_tablename`");

// open the csv file
$fp = fopen($filename,"r");

//parse the csv file row by row
while(($row = fgetcsv($fp,"500",",")) != FALSE)
{
    //insert csv data into mysql table
    $sql = "INSERT INTO Pristabell (Produkt, Pris, Rabattkr, Rabattprosent, Lagerstatus, Butikk, TAGS) VALUES('" . implode("','",$row) . "')";
    if(!mysqli_query($connection, $sql))
    {
        die('Error : ' . mysqli_error($conection));
    }
}
fclose($fp);

//close the db connection
mysqli_close($connection);

?>

Thanks :-)

Hkroed
  • 29
  • 1
  • 10
  • `file_exists` did you tried that? – Gntem Apr 19 '17 at 14:52
  • Test before truncate with `SHOW [FULL] TABLES [{FROM | IN} db_name [LIKE 'pattern' | WHERE expr]` so `SHOW TABLES FROM database LIKE 'my_tablename'`. OK, dont get it right, but will leave the comment. – JustOnUnderMillions Apr 19 '17 at 14:54

2 Answers2

2

http://php.net/manual/en/function.file-exists.php

if(file_exists($pathtofile)){
 //do import
}else{
//stop
}
Peter
  • 748
  • 6
  • 20
0

One simple solution is use

file_exist;

in an if() chunk.

Before the while(), if true continue else exit or trow an exception.