PHP:在truncate table之前检查文件是否存在

时间:2017-04-19 14:51:07

标签: php mysql import truncate

在截断表格之前,有人可以帮我让这个脚本检查文件是否存在。 如果filename不存在,我想停止导入。

<?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);

?>

谢谢: - )

2 个答案:

答案 0 :(得分:2)

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

if(file_exists($pathtofile)){
 //do import
}else{
//stop
}

答案 1 :(得分:0)

一个简单的解决方案是使用

  

file_exist;

在if()块中。

在while()之前,如果为true,则继续退出或抛出异常。