viernes, 14 de febrero de 2025

save csv on db

 <?php

// Database connection

$mysqli = new mysqli("localhost", "username", "password", "database_name");


// Check for connection error

if ($mysqli->connect_error) {

    die("Connection failed: " . $mysqli->connect_error);

}


// Open the CSV file

if (($handle = fopen("data.csv", "r")) !== FALSE) {

    // Skip the first line if it contains the header

    fgetcsv($handle);


    // Prepare the SQL query for inserting data

    $stmt = $mysqli->prepare("INSERT INTO users (name, email, age) VALUES (?, ?, ?)");

    $stmt->bind_param("ssi", $name, $email, $age); // 'ssi' means string, string, integer


    // Read each line of the CSV and insert the data into the database

    while (($data = fgetcsv($handle, 0, ",")) !== FALSE) {

        $name = $data[0];    // First column: name

        $email = $data[1];   // Second column: email

        $age = (int)$data[2]; // Third column: age (cast to integer)


        // Execute the prepared statement

        if (!$stmt->execute()) {

            echo "Error inserting record: " . $stmt->error . "<br>";

        }

    }


    // Close the prepared statement and file handle

    $stmt->close();

    fclose($handle);

} else {

    echo "Error opening the file.";

}


// Close the database connection

$mysqli->close();

?>


No hay comentarios:

Publicar un comentario