2017-04-19 125 views
-2

有人可以帮助我在脚本截断表之前检查文件是否存在。 如果文件名不存在,我想停止导入。PHP:在截断表之前检查文件是否存在

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

?> 

由于:-)

+0

'file_exists'你试过吗? – Gntem

+0

用'SHOW [FULL] TABLES [{FROM | IN} db_name [LIKE'pattern'| WHERE expr]'so'SHOW TABLES FROM database LIKE'my_tablename''。好吧,不要说得对,但会留下评论。 – JustOnUnderMillions

回答

0

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

file_exist;

在if()块中。

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

相关问题