2017-04-19 184 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,則繼續退出或拋出異常。

相關問題