Importing .csv Into Mysql Database - NEED HELP!

free web hosting
Free Web Hosting, No Ads > CONTRIBUTE > Computers > Programming Languages > PHP Programming

Importing .csv Into Mysql Database - NEED HELP!

Mystixs
I need help importing a .csv contents into a Mysql database.
I have this. But its not working.

CODE

<?php
connection = mysql_connect("******", "**********", "********") or die ("Unable
to connect to server");
$db = mysql_select_db("b9_259782_CC", $connection) or die ("Unable to
select database");

fopen ('csvranks.csv', 'r');
mysql_query("INSERT INTO test_table (id, name, guild, level, exp)
?>


What am I doing wrong? The mysql table is all set up..

Any help is GREATLY appreciated. If you need more info just ask.

Thanks!

EDIT: The CSV file looks like this one http://movoda.net/api/csvranks.html

Notice from BuffaloHELP:
Topic modified

 

 

 


Reply

Kubi
Would you mind showing us the error page? It could be an incorrect db nname/password

Reply

master_bacarra
i told you, you haven't looked enough through the search engines tongue.gif

you opened the file, but you didn't use a handle for it.

try this one

CODE

$file_handle = fopen ("filename.csv");

while (($row = fgetcsv($file_handle)) !== false) {
  $data = explode (",",$row);
  $insertrecord =
        "INSER INTO `$tablename` VALUES ('".$data[0]."','".$data[1]."','".$data[2]."','".$data[3]."','".$data[4]."')";
   mysql_query($insterrecord);
}

fclose (file_handle);


i've adjusted the code to fit the csv file you have indicated.

of course that is assumed that all of the values in each row are string. your database could be indicating some of the attributes as of integer type. convert data[3] and data[4] to integer values (i'm assuming that you're keeping the leading zeros in the values of data[0]). i think the function is intval() taking the string as an argument. so the line

CODE

  $insertrecord =
        "INSER INTO `$tablename` VALUES ('".$data[0]."','".$data[1]."','".$data[2]."','".$data[3]."','".$data[4]."')";


will become

CODE

  $insertrecord =
        "INSER INTO `$tablename` VALUES ('".$data[0]."','".$data[1]."','".$data[2]."','".intval($data[3])."','".intval($data[4])."')";



also, change the '$tablename' to the name of the table where these values are to be inserted.
hope that helps (and i hope that works).

 

 

 


Reply

Mystixs
Ok. First, KuBi. I didn't get any error.. It connected to the database, and selected the database. It was just a blank page...

Anyway, master_bacarra thanks, I will try this. I made need more help though. I'm not very good at PHP and Mysql..

Reply

Mystixs
I guess this is because my lack of knowledge and slow learning but i'm having trouble..
I will show what I have now.

The Mysql table:
CODE

ALTER TABLE `test_table` CHANGE `id` `id` INT( 100 ) NOT NULL DEFAULT '0',
CHANGE `name` `name` INT( 100 ) NOT NULL DEFAULT '0',
CHANGE `guild` `guild` INT( 100 ) NOT NULL DEFAULT '0',
CHANGE `level` `level` INT( 100 ) NOT NULL DEFAULT '0',
CHANGE `exp` `exp` INT( 100 ) NOT NULL DEFAULT '0'


The PHP:
CODE


<?php
connection = mysql_connect("sql1.byethost9.com", "***", "***") or die ("Unable
to connect to server");
$db = mysql_select_db("b9_259782_CC", $connection) or die ("Unable to
select database");

$file_handle = fopen ("csvranks.csv");

while (($row = fgetcsv($file_handle)) !== false) {
  $data = explode (",",$row);
    $insertrecord =
        "INSER INTO `tst_table` VALUES ('".$data[0]."','".$data[1]."','".$data[2]."','".intval($data[3])."','".intval($data[4])."')";
   mysql_query($insterrecord);
}

fclose (file_handle);
?>




http://chesspieces.byethost9.com/test.php thats the page its saved to.

I go to it and it does nothing. I check the database table and its empty..

Sorry for the bother..


Reply

master_bacarra
QUOTE(Mystixs @ Jan 27 2007, 10:58 PM) *

The Mysql table:
CODE

ALTER TABLE `test_table` CHANGE `id` `id` INT( 100 ) NOT NULL DEFAULT '0',
CHANGE `name` `name` INT( 100 ) NOT NULL DEFAULT '0',
CHANGE `guild` `guild` INT( 100 ) NOT NULL DEFAULT '0',
CHANGE `level` `level` INT( 100 ) NOT NULL DEFAULT '0',
CHANGE `exp` `exp` INT( 100 ) NOT NULL DEFAULT '0'


i don't get it. you've given me the database entries, but two attributes don't say that it is of INT data type. the id attribute can be of INT, same goes with level and exp. but i don't get it why you're putting name and guild attributes to INT. it doesn't match your table entries indicated in the csv file.

here's one sample data:
0000000073,moc1,CoM,26,594169

assuming that i'm thinking that each entry is under the correct attribute, then 0000000073 is the id, moc1 is the name, CoM is the guild, 26 is the level, and 594169 is the exp. you can't put name and guild as INT because it won't match moc1 and CoM. it won't match the data types.

like what KuBi has said, i think you should post the error here.


QUOTE(Mystixs @ Jan 27 2007, 10:58 PM) *

The PHP:
CODE


<?php
connection = mysql_connect("sql1.byethost9.com", "***", "***") or die ("Unable
to connect to server");
$db = mysql_select_db("b9_259782_CC", $connection) or die ("Unable to
select database");

$file_handle = fopen ("csvranks.csv");

while (($row = fgetcsv($file_handle)) !== false) {
  $data = explode (",",$row);
    $insertrecord =
        "INSER INTO `tst_table` VALUES ('".$data[0]."','".$data[1]."','".$data[2]."','".intval($data[3])."','".intval($data[4])."')";
   mysql_query($insterrecord);
}

fclose (file_handle);
?>




don't forget to put $ before the php variables you're using. put $ before connection and file_handle (the one inside fclose()). query should be INSERT not INSER.

Reply

Mystixs
Thanks. Problems resolved smile.gif

Reply



Got an Opinion! Express your Views! (no registration):-
Add your Reply/ Opinion/ Views/ Comments/ Suggestion/ Questions/ Queries etc.
Posts with decent grammar & English will be accepted and please refrain from profanities.
For asking a Question, We recommend you to sign-up (for free) so that you can track the topic easily.

Nature of your Post*: Opinion/ Reply/ Comments
Question/Query
Feedback to us.
       
Name   Email
Title/Question*

(Maximum characters: 10,000)
You have characters left.
Confirm Code:

Recent Queries:-
  1. how to retrieve leading zero from csv - 48.50 hr back. (1)
  2. character set importin fgetcsv - 94.37 hr back. (1)
Similar Topics

Keywords : importing, csv, mysql, database

  1. Creating A Php Login System Using Mysql
    I need help in creating a login system, what I want is a login system (9)
  2. Mysql Database Not Working
    (3)
    well i'm getting an error message(a databass connection warning) for all of the parts of my site
    that connects to a mysql database i check my database users pertmissions and i try to do the repair
    database thing and it's still not woeking. am i the only person having this or is it an overall
    trap17 issue and how do i fix it.....
  3. Ips Installer Database Details [resolved]
    It wont accept localhost... (6)
    CODE Access denied for user 'skyed211_central'@'localhost' to database
    'skyed211_centralgaming' I get this error message when trying to install my IPB. It will
    not accept localhost, nor mysql. Can I get any help please? I've tried many times to get past
    this part, but it's not happening /sad.gif" style="vertical-align:middle" emoid=":(" border="0"
    alt="sad.gif" />....
  4. The Only Reason I Choose Ms Sql Server Rather Than Mysql
    (0)
    The only reason i choose ms sql server rather than mysql is, MS SQL has more security
    features!! MySQL is lacking a lot in my opinions - Lack in wide char, like nvarchar, I
    developed some application to support chinese letter, and dont know how to build one in mysql - Lack
    in t-sql syntax, like query in query is not fully supported - Does not have today SQL features like
    BI support (today really required) And compare MS SQL to MySQL, the only reason why mysql is
    favourable is - it is free! Dont u guys agree?....
  5. Need Advice On Setting Up Mysql Database.
    I have a huge amount of daily data updates to be inserted. (3)
    First of all, to get the idea of what I am trying to achieve here, please have a look at my
    idea thread, entitled Idea For Using A Cron Job To Grab Daily Travian Map.sql Updates . This gives
    a prelude to the project, what it is for, what it is supposed to do, etc. Now, what I need is
    specific advice on setting up the mySQL database(s) to implement this idea. There is a useful FAQ
    file for how to make use of the map.sql data located on the help.travian.com website, which also
    gives an example of the CREATE TABLE instruction that matches the data in the map.sql fi....
  6. Mysql Db Is Down Getting Following Error
    (2)
    My Mysql is Down can I get some help please? Appreciate it. Patrick Domain: patrickcurl.com Error:
    phpMyAdmin - Error #2002 - The server is not responding (or the local MySQL server's socket is
    not correctly configured)....
  7. It Went Well For A While
    MySQL problem back in all its glory. (5)
    Some time ago I had a stubborn problem when trying to access one of the interactive pages on my
    website and getting the following error: QUOTE Warning: fopen() : open_basedir restriction in
    effect. File(include/errors.xml) is not within the allowed path(s):
    (/home/mrdee:/usr/lib/php:/usr/local/lib/php:/tmp) in
    /home/mrdee/public_html/admin/include/commonfunctions.php on line 682 Warning:
    fopen(include/errors.xml) : failed to open stream: Operation not permitted in
    /home/mrdee/public_html/admin/include/commonfunctions.php on line 682 Cannot open XML data file:
    incl....
  8. Need Help With My Database [resolved]
    retrive data as a link (6)
    This is the situation: I have a database where you can add bands ( theire albums, genre other
    info) For the album part they can add for each album the songs. So what do i want: When i show
    the results there only shoul display the bandname which should be a link to the more detailed info
    like albums biography etc. How do I do that. Is there a name for this and are there any
    tutorials. thx in advance....
  9. Is The Database System Gone Again? [resolved]
    Errors on PHPMyAdmin again (12)
    I wonder if there is a problem with the PHPMyAdmin system again? When trying to get into it, I once
    again get the following: QUOTE Warning: session_write_close() : SQLite: session write query
    failed: database is full in /usr/local/cpanel/base/3rdparty/phpMyAdmin/index.php on line 42
    Warning: session_write_close() : Failed to write session data (sqlite). Please verify that the
    current setting of session.save_path is correct
    (/var/cpanel/userhomes/cpanelphpmyadmin/sessions/phpsess.sdb) in
    /usr/local/cpanel/base/3rdparty/phpMyAdmin/index.php on line 42 Warning: Ca....
  10. Database Or Pdf
    Best way to list books on my site (3)
    Hi all, I am not sure if this is the right place to post but I'm sure you'll tell
    me if it's not. My problem is this: I have a website where I sell books and it's one of
    those simpleton sites where I don't need to know code, I just click icons etc Anyway, I can
    upload images to the server and need to have them in different resolutions and link from a thumbnail
    to the larger picture. What I am trying to say is I have about 6000 books to display on my
    website which is impractical as it takes me about 10 mins to load 1 copy. What is the ....
  11. How Do I Find My Mysql Password? [resolved]
    Cannot access my MySQL (5)
    After all the recent problems, my account has been restored. I have setup my parked domain agin, and
    that works fine. However, I can no longer access my MySQL databases (I can from PHPMyAdmin, but
    that's all). I had to create a new user for my databases, and created the user with exactly the
    same username and password I had before, but some of my web pages do not let me access the pages I
    have associated with my databases. Where could i find out what my DB password is? (Although I am as
    good as sure I am using the right one). I have tried my old password, the new c....
  12. Please Explain Me Mysql
    How do i insert information into this config: (4)
    Hi, I wanted to try just to test how can i connect my website to another mysql server, but i have no
    idea how to insert the other mysql information such as port and host etc.... so here is the config
    file please give me an example CODE <?php // mySQL information $server =
    'FRESHSQL.COM:3306';                   // MySql server $username =
    'vasilevich';                      // MySql Username $password =
    '*******';                         // MySql Password $database =
    'vasilevich';                  // MySql Da....
  13. Remote Access Mysql
    (8)
    Is it possible to directly access my local database from my website? For example, if somebody
    submits info on my website, the info they submitted would be transferred to my local database
    directly. Is that possible? And if so, how do I set that up? The reason I don't want to upload
    my database to my subdomain is because it would be difficult to keep the website database and my
    local database in sync . . . or is there a way to do that? Thanks for any replies.....
  14. Phpmyadmin
    Create new database: No Privileges (7)
    i can not make a sql for diff srcipt, but the sricpt i have is php, DJ-cpanel.. all tho i can not
    install it the error is like this Creating Database Tables No database selected there a mysql
    database is made, but i can not use it for othere stuff... plz note that this is Free script and not
    for paid.. is there a way that the myqsul can not use sql other scripts? or it maybe not working...
    but i am not sure if the script not working or it can be the server may be down on mysql...? ....
  15. Create Table - Mysql Code - Help
    (1)
    I need your feedback about setting the database issues. Please, review them and correct some entries
    in the code if they got some mistakes. This is the code itself: SQL CREATE TABLE
    `news` ( `id` int(250) NOT NULL auto_increment, `title` varchar(255)
    NOT NULL default '', `text` text NOT NULL, `author` varchar(255) NOT
    NULL default '', `valid` varchar(255) NOT NULL default '',
    `date` varchar(255) NOT NULL default '', PRIMARY KEY (`id`) ) ENGINE = ....
  16. Html Form!
    Using MySQL?! (4)
    Hey, I need your help again! I need some good working tutorial how I can update my SQL through
    HTML form. I did use some tutorials online found with the help of google; but they do not work
    properly; I mean there are still small mistakes. I need to have a good tutorial to follow. It
    should be based on security and more things. It has to be done in proper way.......
  17. Mysql, Php, Apache Downloads And Setup Was A Nightmare
    Mysql, PHP, Apache (10)
    Mysql, PHP, Apache downloads were easy enough. Then came the setup process. This seemed to be an
    endless mess of going back and forth trying to get the programs to work together properly. Finaly I
    got them working after about 48 hours. There are great tutorials on the setup process, but only one
    or two actualy were easy enough for me to understand. I would like to see if I was the only one who
    had issues with this setup. Are there easier ways to setup the three?....
  18. Mysql-essential-5.0.51 Installion Problem
    please help me.(urgent) (2)
    Dear friend, please help me. Iam working on php project (matchmaking site). I have downloaded mysql
    essensial 5.0.51. When i was installing mysql 5.0.51, i got following error - Error 1901: Error
    attempting to read from the source installation database:
    c:\windows\installer\527ec6.msi What is solution of this problem ? Iam using
    windows xp professional version 2002 (service pack 2). Please post your reply. Iam waiting for your
    answer. ....
  19. Database With Mysql++
    getting mySQL++ to work with trap17 (7)
    Hi, I'm trying to build an online game and figured the easiest way to do the server list would
    be to make a mySQL database for it; however, I use the con() command on the IP i get from pinging my
    website and I always get an abnormal program termination; however, it will work with the mySQL on my
    own machine. The code is below: CODE #include <iostream> #include <iomanip>
    #include <mysql++> #include "pass.h"//holds my password (i program at
    school) int main(void) {     Connection con("t3jem3_test","....
  20. Mysql Won't Update
    (4)
    Ok, so I'm making some arcade administration software so I don't have to add games the hard
    way, well anyway, one of the features I have is that on the homepage is a featured author and as
    such I just have it so it updates one line in the mySQL. Well, the page with the form passes on the
    varibles fine and the updating page recieves them because I echoed everything, then I build the
    query and I even echo the query and it comes out exactly how I want it to, but for some reason, the
    database itself won't update even though all the varibles are there. Here's....
  21. Qupis : Free Hosting With Php, Mysql, Cpanel. (one Line Text Ad At Bottom)
    a member of Xisto (41)
    Hello Members, We are proud to introduce a new member to Xisto group of sites.
    Qupis : Free Web Hosting 150 MB space, 5000 MB Bandwidth, php,
    mysql, CPanel (Latest). Emails, FTP, Addon domains, Parked Domains etc.
    http://www.Qupis.com
    Feel free to add your reviews and comments about it. -Trap17
    Management ....
  22. Is It Possible To Access The Mysql Remotely?
    (10)
    I like to experiment with a lot of things and I was thinking of making a sort of instant messenger
    in Python, but I want to let people have actual accounts so I need to be able to access the mySQL
    remotely. If that's not possible, are we allowed to run Python scripts on the server?....
  23. Check Referrer To Prevent Linking Yours From Other Sites
    Check referrer with Php and Mysql (8)
    Check Referrer Using Php To Prevent People Linking To Your Downloads From Other Sites Ever
    find that found some people are listing items, images and tuts and linking directly to the download
    url (those that are like my photoshop tutorial.php?id=0), which is a .php to count the number of
    downloads. To prevent this, you can add a piece of code to the download pages that checks which page
    referred them to the download page: if it's my domain, it downloads the file normally, if
    it's not, it will redirect to my home page instead. Important : Not all browser....
  24. Subquery In Mysql
    (5)
    Is there anyway to make subqueries work in MySQL? I'm pretty certain someone out there knows
    how. /smile.gif' border='0' style='vertical-align:middle' alt='smile.gif' /> Can anyone help?
    CODE Select * from ITEMS where ID="Select Max(ID) from ORDERS"; This works
    for MSAccess and SQL Server but why not in MySQL? I'll be writing some reports and I've
    shifted database from MSAccess to MySQL. Help! Thanks.....
  25. Connect To Remote Oracle Database With Toad
    i'm lost (7)
    Hey gang, long time no see, my bad! Anyway, I got me a question. Does anybody know how to
    connect to a remote oracle database using toad? When I read the docs for toad I get the impression
    that I have to have a local oracle installation in order to use toad, but that just seems silly. I
    guess I'm stuck at the point of trying to figure out how to tell toad where to look for all of
    the configuration information it needs for the connection if I don't have any "Oracle Home"
    directories. :crosses fingers: Peace!....
  26. Mysql Database Size
    related to the free database space (6)
    hi all! this is my first post /biggrin.gif' border='0' style='vertical-align:middle'
    alt='biggrin.gif' /> and i have a doubt, how much mysql space i am allowed to use... i mean how
    much is available for my free account....
  27. Import From Excel File Into Mysql Database
    (9)
    Has anyone tried using the excel import function that comes with phpmyadmin
    http://www.phpmyadmin.net/home_page/ - it does not require any additional plug-ins or scripts and
    is fairly straightforward to use. In phpmyadmin, if you click on the database table which you wish
    to import the data to , there is a link on the bottom left corner which says "insert data from a
    text file into the table" - although it says text file it still can be used to import an excel file.
    When you click on this link you will be taken to a page where you will be asked for the file name
    (the....
  28. Increment A Mysql Column
    how to increment a MySQL column one unit (7)
    Hi, I have a column in a MySQL table which contains a counter of the views of the object described
    by this table. I would like to increment this value by one everytime the object is viewed. Obviously
    came into my mind the possibility of retrieving the value of this field, store it in a variable
    increment this value by one and perform an UPDATE query again with this new value. My question is if
    there is a MySQL option to update the field with its actual value plus an unit increment. I hope you
    understand the issue.....
  29. Complete Login System
    With PHP + MYSQL (57)
    Its an complete login sistem made and tested by me and I think itwill be very usefull for people who
    are tryn to learn PHP. First, let's make register.php: CODE <?
    include("conn.php"); // create a file with all the database connections
    if($do_register){ // if the submit button were clicked if((!$name)
    || (!$email) || (!$age) || (!$login) ||
    (!$password) || (!$password2)){ print "You can't let
    any fields in blank....
  30. Mysql Database Setup : Setting Up Mysql Database
    Guide to use MySQL database in your site (6)
    A SMALL INTRODUCTION TO DATABASE ============================= I have seen that many members have
    problems with Database. Here is a small INFO which should give you the IDEA. mySQL is a DATABASE
    server. You can access it using the link in Cpanel. Cpanel can be accessed by
    "www.YOUR-SITE.com/Cpanel" There you have 4 Main Options :- 1> CREATE A DATABASE 2> CREATE A USER
    3> ADD USER TO DATABASE 4> PHPMYADMIN CREATE : IT ALLOWS YOU TO CREATE A DATABASE CREATE USER
    : IT ALLOWS YOU TO CREATE A USER. USING THIS, YOU CAN ACCESS THE DATABASE. A DATABASE CANNOT BE....

    1. Looking for importing, csv, mysql, database

*RANDOM STUFF*





*SIMILAR VIDEOS*
Searching Video's for importing, csv, mysql, database

*MORE FROM TRAP17.COM*
Similar
Creating A Php Login System Using Mysql - I need help in creating a login system, what I want is a login system
Mysql Database Not Working
Ips Installer Database Details [resolved] - It wont accept localhost...
The Only Reason I Choose Ms Sql Server Rather Than Mysql
Need Advice On Setting Up Mysql Database. - I have a huge amount of daily data updates to be inserted.
Mysql Db Is Down Getting Following Error
It Went Well For A While - MySQL problem back in all its glory.
Need Help With My Database [resolved] - retrive data as a link
Is The Database System Gone Again? [resolved] - Errors on PHPMyAdmin again
Database Or Pdf - Best way to list books on my site
How Do I Find My Mysql Password? [resolved] - Cannot access my MySQL
Please Explain Me Mysql - How do i insert information into this config:
Remote Access Mysql
Phpmyadmin - Create new database: No Privileges
Create Table - Mysql Code - Help
Html Form! - Using MySQL?!
Mysql, Php, Apache Downloads And Setup Was A Nightmare - Mysql, PHP, Apache
Mysql-essential-5.0.51 Installion Problem - please help me.(urgent)
Database With Mysql++ - getting mySQL++ to work with trap17
Mysql Won't Update
Qupis : Free Hosting With Php, Mysql, Cpanel. (one Line Text Ad At Bottom) - a member of Xisto
Is It Possible To Access The Mysql Remotely?
Check Referrer To Prevent Linking Yours From Other Sites - Check referrer with Php and Mysql
Subquery In Mysql
Connect To Remote Oracle Database With Toad - i'm lost
Mysql Database Size - related to the free database space
Import From Excel File Into Mysql Database
Increment A Mysql Column - how to increment a MySQL column one unit
Complete Login System - With PHP + MYSQL
Mysql Database Setup : Setting Up Mysql Database - Guide to use MySQL database in your site
advertisement



Importing .csv Into Mysql Database - NEED HELP!



 

 

 

 

ADD REPLY / Got an Opinion! a humble request :-) RAPID SEARCH! Free Hosting [X]
Express your Opinions, Thoughts or Contribute more info. to help others.
Ask your Doubts & Queries to get answers, So that "Together We can help others!"
Register FREE for AD-FREE forum, Create your own topics, Ask Questions, track topics, setup subscriptions & notifications and Get a Free Website w/ Email and FTP.
500MB Space *No Ads*, CPanel, FTP, PHP, MySQL, EMails - 100% FREE