【问题标题】:PHP: Check if file exists before truncate table [duplicate]PHP:在截断表之前检查文件是否存在[重复]
【发布时间】:2017-09-15 21:17:01
【问题描述】:

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

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

?>

谢谢:-)

【问题讨论】:

  • file_exists 你试过了吗?
  • 使用SHOW [FULL] TABLES [{FROM | IN} db_name [LIKE 'pattern' | WHERE expr] 截断之前测试SHOW TABLES FROM database LIKE 'my_tablename'。好的,不正确,但会留下评论。

标签: php mysql import truncate


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

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

    文件存在;

    在 if() 块中。

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

    【讨论】:

      猜你喜欢
      • 2018-02-20
      • 2020-11-16
      • 2015-11-22
      • 2015-02-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-07
      • 2014-07-13
      相关资源
      最近更新 更多