read users from csv file and add them to a database in php

main.php
// assuming the csv file has headers for each column
$csv_file = 'users.csv';

// establish database connection
$connection = mysqli_connect('localhost', 'username', 'password', 'database_name');

if (!$connection) {
    die('Error: Could not connect to database - ' . mysqli_connect_error());
}

// open csv file for reading
if (($handle = fopen($csv_file, "r")) !== FALSE) {
    // get headers from csv file
    $headers = fgetcsv($handle, 1000, ",");
    
    // loop through each row in csv file
    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
        // combine headers with row data to create associative array
        $user_data = array_combine($headers, $data);
        
        // sanitize user data to prevent SQL injection
        $user_data = array_map(function($value) use ($connection) {
            return mysqli_real_escape_string($connection, $value);
        }, $user_data);
        
        // insert user data into database
        $query = "INSERT INTO users (name, email, phone) 
                  VALUES ('" . $user_data['name'] . "', '" . $user_data['email'] . "', '" . $user_data['phone'] . "')";
                  
        if (!mysqli_query($connection, $query)) {
            echo "Error inserting data: " . mysqli_error($connection) . "\n";
        }
    }
    fclose($handle);
}
mysqli_close($connection);
echo "Data imported successfully";
1384 chars
38 lines

In the above code, we first establish a connection with the MySQL database using the mysqli_connect() function.

Next, we open the CSV file using the fopen() function and read the headers and the data using the fgetcsv() function.

We then create an associative array using the headers and the data, and sanitize the user data using the mysqli_real_escape_string() function to prevent SQL injection.

Finally, we insert the sanitized user data into the MySQL database using the mysqli_query() function within a loop that goes through all the rows of the CSV file.

At the end, we close the CSV file and MySQL database connections and output a success message.

related categories

gistlibby LogSnag