Importing data from a CSV file into a MySQL database is a common requirement in web development, especially when dealing with data from spreadsheets or exporting tools. In this blog post, we’ll walk through a PHP script that automates the process of importing CSV data into a dynamically created MySQL table.

Overview

This tutorial demonstrates how to:

  1. Upload a CSV file using a PHP form.
  2. Read the CSV file and determine the maximum length of data for each column.
  3. Create a new table in a MySQL database with dynamically determined column lengths.
  4. Insert the CSV data into the newly created table.
  5. Provide feedback on the success of the operation.

Prerequisites

Before diving into the code, ensure you have the following setup:

  • A MySQL database and user account with permissions to create tables and insert data.
  • A PHP environment, such as XAMPP, WAMP, or a server running PHP and MySQL.
  • Basic knowledge of PHP and MySQL.

The PHP Script

Here’s the complete PHP script that performs the CSV import:

Code Explanation

Let’s break down the script and understand how it works step by step:

Step 1: Database Connection

The script begins by establishing a connection to the MySQL database using the mysqli extension:

Replace your_username, your_password, and your_database with your actual database credentials.

Step 2: File Upload Form

The HTML form allows users to upload a CSV file:

Step 3: Reading and Analyzing the CSV File

When the form is submitted, the script reads the CSV file and determines the maximum length of data for each column:

 

Step 4: Creating the MySQL Table

Using the maximum lengths determined, the script creates a new table with appropriate column sizes:

The table name is generated randomly to avoid collisions with existing tables.

Step 5: Inserting CSV Data into the Table

After creating the table, the script inserts the CSV data into the new table:

 

Step 6: Displaying the Result

Finally, the script outputs the result of the operation, including the table name and success message:

Conclusion

This PHP script efficiently imports CSV data into a MySQL database by dynamically determining the appropriate column lengths. This approach ensures optimal use of database resources while providing flexibility to handle varying data sizes.

Feel free to customize the script to suit your specific needs, such as adding error handling or supporting additional CSV formats. By understanding each step, you can extend and adapt the script to integrate with larger systems or automate regular data imports.

With this solution, you can easily manage data from CSV files, providing a seamless bridge between various data sources and your MySQL database.