How to Upload a CSV file into a MySQL Database Using PHP

Are you wondering how you can upload a CSV file into a MySQL database using PHP? Well if you are, you are in the right place!

In our example, we are going to be using Bootstrap and mysqli for the database connection. See below the full script needed in order to complete this action:


<div id="primary" class="content-area">
	<main id="main" class="site-main" role="main">

    <div class="container">

      <div class="section">

        <?php

        $db = new mysqli('localhost', 'username', 'password', 'databasename');

        if($db->connect_errno > 0){
            die('Unable to connect to database [' . $db->connect_error . ']');
        } 


          // File Upload

          if (isset($_POST['submit'])) {
             
                   
              // Import the uploaded file to the database

              $handle = fopen($_FILES['filename']['tmp_name'], "r");

               while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {

                  $sql = "INSERT INTO `tablename` (`field1`, `field2`, `field3`, `field4`, `field5`, `field6`, `field7`) VALUES ($data[0], '$data[1]', '$data[2]', '$data[3]', '$data[4]', '$data[5]', $data[6]);";

                  if(!$result = $db->query($sql)){
                      die('There was an error running the query [' . $db->error . ']');
                  }
              }

              fclose($handle);

              echo "Import Completed Successfully"; 
              mysqli_close($db);
          }

          else {
                
             echo "<center>";
              echo "<div class='col-md-12'>";

              echo "<h1>Upload Vouchers CSV File. </h1><br />\n"; 
              echo "<form enctype='multipart/form-data' action='/voucher-import/' method='post'>"; 
              echo "File name to import:<br /><br />\n";
              echo '<input type="file" class="filestyle" name="filename" data-iconName="glyphicon-inbox" required><p>&nbsp;&nbsp;</p><p></p>';
              echo "<input class='btn'  type='submit' name='submit' value='Import'><p></p></form>";
          }
             echo "</div>";
             echo "</center>";
          ?>
          </div>

      </div>


	</main><!-- #main -->
</div><!-- #primary -->

In the example provided above, we are inserting a CSV file with 7 columns where all rows within the CSV are looped and inserted into the database.

The main things that will need editing are first the database connection, so you will need to replace the following line:


$db = new mysqli('localhost', 'username', 'password', 'databasename');

The other part that will need changing is INSERT statement shown below:


$sql = "INSERT INTO `tablename` (`field1`, `field2`, `field3`, `field4`, `field5`, `field6`, `field7`) VALUES ($data[0], '$data[1]', '$data[2]', '$data[3]', '$data[4]', '$data[5]', $data[6]);";

So firstly, you would change the tablename to match the table you would like to insert the data to. If you have less/more columns, you will have to remove/add fields and values to match how many columns you have in your database.

If you are inserting NULL values, you can replace the $data[x] value with NULL. Let’s say your first column is an ID (auto-increment), you can simply replace $data[0] with NULL.

Do remember, for this to work, you will need to upload CSV files that are comma-separated.

And just like that, you now have an awesome CSV upload script!

If this has helped you out, leave a comment below. If for some reason you cannot get this to work, get in touch, we always love helping people!

 

Nathan da Silva - Profile

Posted by: Nathan da Silva

Nathan is the Founder of Silva Web Designs. He is passionate about web development, website design and basically anything digital related. His main expertise is with WordPress, Magento, Shopify as well as many other frameworks. Whether you need responsive design, SEO, speed optimisation or anything else in the world of digital then get in touch. If you would like to work with Nathan, simply drop him an email at [email protected]

It’s good to share

Create a new WordPress admin user in the database

You can create a new WordPress admin user from within the database using phpMyAdmin.

Method 1

1.) Log into phpMyAdmin (cPanel / Plesk / Web Hosting / Managed WordPress).

2.) Click the _users table

3.) Click the Insert tab

4.) Fill in the following fields.

  • ID is any number you choose
  • user_login is the username for accessing the WordPress Dashboard.
  • user_pass is the password for the user. Make sure to select MD5 in the functions menu
  • user_nicename is the nickname for the user
  • user_email is the email address you want to associate with this user
  • user_registered is the date and time for when this user is registered
  • user_status should be set to 0
  • display_name is the name that will be displayed for this user on your site

5.) Click the Go button

6.) Click the _usermeta table

7.) Click the Insert tab

8.) Fill in the following fields:

  • user_id is the ID you entered in the previous step
  • meta_key should be the phrase wp_capabilities
  • meta_value should be

a:1:{s:13:"administrator";s:1:"1";}

9.) Click Go

10.) Click the Insert tab again

11.) Enter the following information:

  • user_id is the same number you entered in the previous step
  • meta_key should be the phrase wp_user_level
  • meta_value should be the number 10

12.) Click the Go button.

You can now login with the new Admin user.

Method 2

For developers who want to speed this process up, you can simply drop this SQL query in your database:-


INSERT INTO `databasename`.`wp_users` (`ID`, `user_login`, `user_pass`, `user_nicename`, `user_email`, `user_url`, `user_registered`, `user_activation_key`, `user_status`, `display_name`) VALUES ('4', 'demo', MD5('demo'), 'Your Name', '[email protected]', 'http://www.test.com/', '', '', '0', 'Your Name');
 
INSERT INTO `databasename`.`wp_usermeta` (`umeta_id`, `user_id`, `meta_key`, `meta_value`) VALUES (NULL, '4', 'wp_capabilities', 'a:1:{s:13:"administrator";s:1:"1";}');
 
INSERT INTO `databasename`.`wp_usermeta` (`umeta_id`, `user_id`, `meta_key`, `meta_value`) VALUES (NULL, '4', 'wp_user_level', '10');

Remember to change the databasename to the database you are working with. Also don’t forget to change the appropriate values.

 

Nathan da Silva - Profile

Posted by: Nathan da Silva

Nathan is the Founder of Silva Web Designs. He is passionate about web development, website design and basically anything digital related. His main expertise is with WordPress, Magento, Shopify as well as many other frameworks. Whether you need responsive design, SEO, speed optimisation or anything else in the world of digital then get in touch. If you would like to work with Nathan, simply drop him an email at [email protected]

It’s good to share