Jump to content

Inserting data from CSV File


gdk123

Recommended Posts

Hi!You could use explode() (or split() if you want regular expessions), which splits the string into an array, and then add the info into an db.Example:

// Connecting, selecting database$link = mysql_connect('mysql_host', 'mysql_user', 'mysql_password')   or die('Could not connect: ' . mysql_error());mysql_select_db('my_database') or die('Could not select database');$text = file_get_contents( 'file.txt' );$info = explode( ',', $text );// Performing SQL query$query = "INSERT INTO my_table (field1,field2,field3) VALUES('".$info[0]."','".$info[1]."','".$info[2]."')";mysql_query($query) or die('Query failed: ' . mysql_error());// Closing connectionmysql_close($link);

If the info also is seperated by newlines (or such), you could do like this:

// Connecting, selecting database$link = mysql_connect('mysql_host', 'mysql_user', 'mysql_password')   or die('Could not connect: ' . mysql_error());mysql_select_db('my_database') or die('Could not select database');$text = file_get_contents( 'file.txt' );$lines = explode( "\n", $text );foreach ( $lines as $line ) {   $info = explode( ',', $line );   // Performing SQL query   $query = "INSERT INTO my_table (field1,field2,field3) VALUES('".$info[0]."','".$info[1]."','".$info[2]."')";   mysql_query($query) or die('Query failed: ' . mysql_error());}// Closing connectionmysql_close($link);

In the last example you could use file() instead of file_get_contents() and explode(), as file() returns an array with the lines. Please note that in the case of file() you also get the newline at the end of each line/string, which you don't get from explode.Hope that helped.Good Luck and Don't Panic!

Link to comment
Share on other sites

Hi.. Open phpmyadmin and select any db then select any table then select sql: that will open sql query textbox area.. under that there is small link having text: "Insert data from a text file into the table " Click this you will get it.. Regards, Vijay

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...