How can PHP be used to read data from a CSV file and transfer it to a MySQL database for a shop system?

To transfer data from a CSV file to a MySQL database for a shop system, you can use PHP to read the CSV file line by line, parse the data, and insert it into the MySQL database using SQL queries. This can be achieved by opening the CSV file, reading its contents, connecting to the MySQL database, and executing INSERT queries for each row of data.

<?php
// Connect to MySQL database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "shop_system";

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

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

// Open CSV file
$csvFile = 'products.csv';
$handle = fopen($csvFile, 'r');

// Read CSV file line by line
while (($data = fgetcsv($handle, 1000, ',')) !== FALSE) {
    $name = $data[0];
    $price = $data[1];
    $quantity = $data[2];

    // Insert data into MySQL database
    $sql = "INSERT INTO products (name, price, quantity) VALUES ('$name', '$price', '$quantity')";
    if ($conn->query($sql) === TRUE) {
        echo "Data inserted successfully";
    } else {
        echo "Error: " . $sql . "<br>" . $conn->error;
    }
}

// Close CSV file and MySQL connection
fclose($handle);
$conn->close();
?>