PHP MySQL Insert with Load DATA Local INFILE
From w3cyberlearnings
Contents |
PHP MySQL INSERT Record From File
Insert records from text file.
Syntax
- student.txt is a file that contain records to be inserted
- Field within the student.txt file separate by -
- Last line terminated by :
$insert_query = "LOAD DATA LOCAL INFILE 'student.txt' INTO table student FIELDS TERMINATED BY '-' LINES TERMINATED BY ':' (last_name,first_name) "; mysql_query($insert_query, $connection);
File Content (student.txt)
lee-salina:so-pheank:lee-lyekwan:otam-kiloma
Example 1
<?php define('HOST', 'localhost'); define('USER', 'root'); define('PASS', 'yeething'); define('DBNAME', 'woowood'); $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 $insert_query = "LOAD DATA LOCAL INFILE 'student.txt' INTO table student FIELDS TERMINATED BY '-' LINES TERMINATED BY ':' (last_name,first_name) "; if (!mysql_query($insert_query, $connection)) { echo "Can't insert student record : " . mysql_error($connection); } else { echo "You have successfully insert records into student table"; } } } mysql_close($connection); ?>
Output
You have successfully insert records into student table