title: Importing CSV to MySQL with PHP
body: <p>I have gathered some information from the Internet and wrote this small script to import a CSV file into a MySQL database. I think it is correct, but it's not working.</p>
  
  <p>What am I doing wrong?</p>
  
  <pre><code> &lt;?php 
  
  //connect to the database
  $connect = mysql_connect("localhost","testdb","testdb");
  mysql_select_db("testdb",$connect); //select the table    
  
  if ($_FILES[csv][size] &gt; 0) {
  
      //get the csv file
      $file = $_FILES[csv][tmp_name];
      $handle = fopen($file,"r");
  
      //loop through the csv file and insert into database
      do {
          if ($data[0]) {
              mysql_query("INSERT INTO class12 (htno, subcode, subname, int_marks, ext_marks, result, credits) VALUES
                  (
                      '".addslashes($data[0])."',
                      '".addslashes($data[1])."',
                      '".addslashes($data[2])."'
                      '".addslashes($data[3])."'
                      '".addslashes($data[4])."'
                      '".addslashes($data[5])."'
                      '".addslashes($data[6])."'
                      '".addslashes($data[7])."'
                  )
              ");
          }
      } while ($data = fgetcsv($handle,3000,",","'"));
      //
  
      //redirect
      header('Location: import.php?success=1'); die;
  
  }
  
  ?&gt;
  
  &lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt;
  &lt;html xmlns="http://www.w3.org/1999/xhtml"&gt;
  &lt;head&gt;
  &lt;meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /&gt;
  &lt;title&gt;Import a CSV File&lt;/title&gt;
  &lt;/head&gt;
  
  &lt;body&gt;
  
  &lt;?php if (!empty($_GET[success])) { echo "&lt;b&gt;Your file has been imported.&lt;/b&gt;&lt;br&gt;&lt;br&gt;"; } //generic success notice ?&gt;
  
  &lt;form action="" method="post" enctype="multipart/form-data" name="form1" id="form1"&gt;
    Choose your file: &lt;br /&gt;
    &lt;input name="csv" type="file" id="csv" /&gt;
    &lt;input type="submit" name="Submit" value="Submit" /&gt;
  &lt;/form&gt;
  
  &lt;/body&gt;
  &lt;/html&gt;
  </code></pre>
  
  <p>If possible, someone please include the code to auto-create an SQL table with a filename (without <code>.csv</code> extension) and then importing it.</p>