How can PHP be used to insert data from a CSV file into a database?

To insert data from a CSV file into a database using PHP, you can read the CSV file line by line, parse each line to get the data, and then insert it into the database using SQL queries. This can be done using PHP functions like fopen(), fgetcsv(), and mysqli_query().

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Open the CSV file for reading
$csvFile = fopen('data.csv', 'r');

// Loop through each line in the CSV file
while (($data = fgetcsv($csvFile)) !== FALSE) {
    // Insert data into the database
    $sql = "INSERT INTO table_name (column1, column2, column3) VALUES ('" . $data[0] . "', '" . $data[1] . "', '" . $data[2] . "')";
    $conn->query($sql);
}

// Close the CSV file
fclose($csvFile);

// Close the database connection
$conn->close();
?>