2016-03-08 59 views
0

我想用下面的情形:我需要DROP TABLE如果不存在則CREATE TABLE然後LOAD DATA LOCAL INFILE

DROP TABLE如果不存在則CREATE TABLE然後LOAD DATA LOCAL INFILE。

錯誤

無法插入portmailredirect_data.csv記錄:表 'duncanho_csvtest.pmr_user_data' 不存在

代碼:

<?php 

define('HOST', 'localhost'); 
define('USER', 'duncanho_csvtest'); 
define('PASS', '271288Drh!'); 
define('DBNAME', 'duncanho_csvtest'); 

$connection = mysql_connect(HOST, USER, PASS); 

if (!$connection) { 
    die("can not connect to the server!<br/>"); 
} else { 
    $rdb = mysql_select_db(DBNAME); 
    if (!$rdb) { 
     die("The " . DBNAME . "database could not be selected"); 
    } else { 

// insert to the student table query 
     $sql = 'DROP TABLE IF EXISTS `pmr_user_data`'; 
     mysql_query($sql, $connection); 

$sql2 = 'CREATE TABLE `pmr_user_data` (
`id` TINYINT(3) UNSIGNED NOT NULL AUTO_INCREMENT, 
`customer_code` INT(10) NOT NULL, 
`service` VARCHAR(30) NOT NULL, 
`primary_name` VARCHAR(50) NOT NULL, 
`secondary_name` VARCHAR(50) NOT NULL, 
`email` VARCHAR(50) NOT NULL, 
`start_date` DATE NOT NULL, 
`end_date` DATE NOT NULL, 
`letters_recieved` VARCHAR(50) NOscenarioT NULL, 
`last_mail` VARCHAR(50) NOT NULL, 
`reg_date` VARCHAR(50) NOT NULL, 
)'; 
mysql_query($sql2, $connection); 

$insert_query = " 
     LOAD DATA LOCAL INFILE 'portmailredirect_data.csv' 
          REPLACE INTO TABLE pmr_user_data 
          FIELDS TERMINATED BY ',' 
          LINES TERMINATED BY '\r\n' 
          IGNORE 1 ROWS 
(customer_code,service,primary_name,secondary_name,email,start_date,end_date,letters_recieved,postage_fund,last_mail) 
       "; 

     if (!mysql_query($insert_query, $connection)) { 
      echo "Can't insert portmailredirect_data.csv records : " . mysql_error($connection); 
     } else { 
      echo "You have successfully insert records into student table"; 
     } 
    } 
} 
mysql_close($connection); 
?> 

任何幫助讚賞。

+0

我看到的第一件事是,你的創建聲明是不正確的...也許檢查錯誤也存在。最後一個NOT NULL不應該以','結尾,因爲沒有下一個要創建的列 – Xavjer

回答

0

您的'創建表'查詢無法創建表,因爲您沒有提到自動遞增列的主鍵。

$sql2 = 'CREATE TABLE `pmr_user_data` (
`id` TINYINT(3) UNSIGNED NOT NULL AUTO_INCREMENT, 
`customer_code` INT(10) NOT NULL, 
`service` VARCHAR(30) NOT NULL, 
`primary_name` VARCHAR(50) NOT NULL, 
`secondary_name` VARCHAR(50) NOT NULL, 
`email` VARCHAR(50) NOT NULL, 
`start_date` DATE NOT NULL, 
`end_date` DATE NOT NULL, 
`letters_recieved` VARCHAR(50) NOT NULL, 
`last_mail` VARCHAR(50) NOT NULL, 
`reg_date` VARCHAR(50) NOT NULL, 
PRIMARY KEY (`id`) 
)'; 

在上面的代碼'PRIMARY KEY'爲第一個自動增量列定義。這應該工作。