CSV to MySQL
unknown
php
2 years ago
1.0 kB
7
Indexable
<?php
// Connect to your MySQL database
$servername = "your_server";
$username = "your_username";
$password = "your_password";
$database = "your_database";
$conn = new mysqli($servername, $username, $password, $database);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Read the .CSV file
$csvFile = "your_file.csv";
$data = array_map('str_getcsv', file($csvFile));
$columns = $data[0]; // Assuming the first row contains column names
// Create a new table with the same column names
$sql = "CREATE TABLE IF NOT EXISTS your_table (";
foreach ($columns as $column) {
$sql .= "`$column` VARCHAR(255), ";
}
$sql = rtrim($sql, ", ") . ")";
$conn->query($sql);
// Insert data into the newly created table
for ($i = 1; $i < count($data); $i++) {
$values = "'" . implode("', '", $data[$i]) . "'";
$insertQuery = "INSERT INTO your_table (" . implode(", ", $columns) . ") VALUES ($values)";
$conn->query($insertQuery);
}
// Close the database connection
$conn->close();
?>
Editor is loading...