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();
?>
Keywords
Related Questions
- Are there any specific PHP libraries or tools recommended for working with PDF files in PHP?
- In what situations would it be advisable for a PHP beginner to focus on mastering basic PHP functions and syntax before delving into object-oriented programming concepts like class definitions?
- What are some best practices for error handling in PHP to avoid notices and warnings like "Undefined variable"?