从表中删除列

时间:2016-05-02 17:48:17

标签: php mysql

我将.csv文件数据导入到mysql表中。每次我运行代码时我喜欢做什么我想要删除所有列和数据并用更新的.csv内容替换它。

   $affectedRows = $pdo->exec("
     //HERE I do need additional code to drop column data from $databasetable similar to following
  /*------------------------------------------*/
    DROP TABLE IF EXISTS '$databasetable'

    CREATE TABLE IF NOT EXISTS `$databasetable` (
          Column names1
          Column name 2
          .
     ) ENGINE=MyISAM DEFAULT CHARSET=utf8;
  /*------------------------------------------*/


     LOAD DATA LOCAL INFILE ".$pdo->quote($csvfile)." INTO TABLE `$databasetable`
     FIELDS TERMINATED BY ".$pdo->quote($fieldseparator)."
     LINES TERMINATED BY ".$pdo->quote($lineseparator));

2 个答案:

答案 0 :(得分:1)

我认为你想要做的是 TRUNCATE 问题中的表格。那就是删除表中的所有数据但不删除表本身,对吧? 所以,这里有1个提示:

<?php 
    //FIRST TRUNCATE (REMOVE OLD DATA IN THE TABLE $databasetable
    $stmt      = $db->prepare("TRUNCATE TABLE {$databasetable}");
    $tblEmpty  = $stmt->execute();

    //NOW, ONCE THE TABLE'S BEEN TRUNCATED; YOU MAY CONTINUE WITH THE NEW "INSERTS"...
    if($tblEmpty){
        // INSERT THE DATA FROM THE CSV...
    }

    //...
    //...
    // MORE CODE HERE...

答案 1 :(得分:0)

 $affectedRows = $pdo->exec("
 //HERE I do need additional code to drop column data from $databasetable similar to following
 /*------------------------------------------*/
/* I REMOVED THE SINGLE QUOTESFROM $databasetable and I was able to drop the table. Once the table was dropped then I was able to create the $databasetable which solved the problem. 
DROP TABLE IF EXISTS $databasetable;
CREATE TABLE IF NOT EXISTS `$databasetable` (
      Column names1
      Column name 2
      .
 ) ENGINE=MyISAM DEFAULT CHARSET=utf8;
/*------------------------------------------*/


 LOAD DATA LOCAL INFILE ".$pdo->quote($csvfile)." INTO TABLE `$databasetable`
 FIELDS TERMINATED BY ".$pdo->quote($fieldseparator)."
 LINES TERMINATED BY ".$pdo->quote($lineseparator));