-
Create and Delete and Recreate Table
over 8 years ago
-
over 8 years ago
Hi Warren,
Please find below the code packet as a solution to your problem I am attaching a sample CSV file also. Please try and let me know if you face any problem
- include 'dbconn.php';
- $drop_query = 'DROP TABLE IF EXISTS `test`.`tbl_user`';
- $create_query = 'CREATE TABLE `test`.`tbl_user` ( `id` int(11) NOT NULL AUTO_INCREMENT, `fname` varchar(50) DEFAULT NULL, `lname` varchar(50) DEFAULT NULL, `email` varchar(50) DEFAULT NULL, `password` varchar(50) DEFAULT NULL, PRIMARY KEY (`id`) ) ';
- $field_separator = '\'\t\''; //character which seperates the fields in csv file it can other than \t
- $line_separator = '\'\n\''; //character which seperates the records in csv file it can other than \n
- $csv_file = 'test.csv';
- $import_query = ' LOAD DATA LOCAL INFILE \''.$csv_file.'\' INTO TABLE `test`.`tbl_user` FIELDS TERMINATED BY '.$field_separator.' LINES TERMINATED BY '.$line_separator;
- // the import query should look like LOAD DATA LOCAL INFILE 'test.csv' INTO TABLE `test`.`tbl_user` FIELDS TERMINATED BY '\t' LINES TERMINATED BY '\n'
- if(!file_exists($csv_file)) {
- die("File not found. Make sure you specified the correct path.");
- }
- mysqli_query($DBConnect,$drop_query); // drop the table if it exists
- mysqli_query($DBConnect,$create_query); //create the table
- mysqli_query($DBConnect,$import_query); // import the csv file
- $rows_imported = mysqli_affected_rows($DBConnect); // returns how many rows are affected/inserted
- echo $rows_imported.' row(s)affected';
-
1 Answer(s)