Month: November 2024

Export MySQL data into CSV using PHP

To fetch data from a MySQL database and export it to CSV using PHP, you can follow these steps:

<?php
// Database connection details
$servername = "localhost";
$username = "your_username";
$password = "your_password";
$dbname = "your_database_name";

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

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

// Fetch data from your table
$sql = "SELECT * FROM your_table";
$result = $conn->query($sql);

// Check if any rows are returned
if ($result->num_rows > 0) {
    // Define CSV filename
    $filename = "exported_data.csv";

    // Set headers for CSV download
    header('Content-Type: text/csv');
    header('Content-Disposition: attachment; filename="' . $filename . '"');

    // Create a file pointer connected to the output stream
    $output = fopen('php://output', 'w');

    // Output CSV header
    $header = array('ID', 'Name', 'Email');
    fputcsv($output, $header);

    // Output data from rows
    while ($row = $result->fetch_assoc()) {
        fputcsv($output, $row);
    }

    // Close the file pointer
    fclose($output);
} else {
    echo "No data found";
}

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

Explanation:

  1. Database Connection: Replace your_username, your_password, your_database_name, and your_table with your actual database credentials and table name.
  2. Fetch Data: The SQL query retrieves data from the specified table.
  3. CSV Headers: The header function is used to set headers for CSV download.
  4. CSV File Creation: We use fopen to create a file pointer connected to the output stream (php://output). Then, fputcsv is used to write the CSV header and data.
  5. Download CSV: Headers are set to prompt the user to download the CSV file with the specified filename.

When you run this script, it will fetch data from your MySQL table and export it to a CSV file, which will be downloaded by the user.

Import CSV data into MySQL using PHP

Here’s a detailed example of how to import data from a CSV file into a MySQL database using PHP. The script processes each row one by one, displays a success message for each successfully inserted row, and stops the process if any error occurs, showing the error message.

Prerequisites:

  1. Ensure you have a MySQL database and table set up to store the CSV data.
  2. Adjust the database connection details and table schema as needed.

Database Setup:

Assume you have a MySQL table named csv_import with columns id, name, and email.

CREATE TABLE csv_import (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(255) NOT NULL,
    email VARCHAR(255) NOT NULL
);

Here’s a PHP script that handles the CSV import process:

<?php
// Database connection details
$servername = "your_servername";
$username = "your_username";
$password = "your_password";
$dbname = "your_dbname";

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

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

if (isset($_POST['submit'])) {
    $csvFile = $_FILES['csv']['tmp_name'];

    if (is_file($csvFile)) {
        // Open the CSV file
        if (($handle = fopen($csvFile, "r")) !== FALSE) {
            $rowNumber = 0;

            // Process each row of the CSV file
            while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
                $rowNumber++;

                // Skip the header row
                if ($rowNumber == 1) {
                    continue;
                }

                $name = $conn->real_escape_string($data[0]);
                $email = $conn->real_escape_string($data[1]);

                // Insert the data into the database
                $sql = "INSERT INTO csv_import (name, email) VALUES ('$name', '$email')";
                
                if ($conn->query($sql) === TRUE) {
                    echo "Row $rowNumber inserted successfully.<br>";
                } else {
                    echo "Error inserting row $rowNumber: " . $conn->error . "<br>";
                    break;
                }
            }

            fclose($handle);
        } else {
            echo "Error opening the CSV file.";
        }
    } else {
        echo "Invalid file.";
    }
}
$conn->close();
?>
Here the HTML to upload CSV file

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>CSV Import</title>
</head>
<body>
    <form action="" method="post" enctype="multipart/form-data">
        <label for="csv">Choose CSV file:</label>
        <input type="file" name="csv" id="csv" required>
        <button type="submit" name="submit">Import CSV</button>
    </form>
</body>
</html>

Explanation:

  1. Database Connection: Establish a connection to the MySQL database using the mysqli extension.
  2. Form Handling: The script checks if the form is submitted and processes the uploaded CSV file.
  3. CSV File Processing: It opens the CSV file and processes each row one by one using a while loop.
    It skips the header row.
    It escapes the data using $conn->real_escape_string to prevent SQL injection.
    It inserts the data into the csv_import table.
    It shows a success message for each inserted row.
    If any error occurs, it shows an error message and stops the process.
  4. HTML Form: The form allows the user to upload a CSV file.

Print total of a variable inside while loop outside of the loop

To accumulate values from a MySQL query inside a while loop and then calculate the total value outside the loop, you can use a variable to store the total value while iterating through the records. Here’s an example in PHP:

<?php
// Your database connection parameters
$servername = "localhost";
$username = "your_username";
$password = "your_password";
$database = "your_database";

// Create a connection to the MySQL database
$conn = new mysqli($servername, $username, $password, $database);

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

$totalValue = 0; // Initialize total value

// Your SQL query
$sql = "SELECT value_column FROM your_table_name WHERE your_conditions";

$result = $conn->query($sql);

if ($result->num_rows > 0) {
    while ($row = $result->fetch_assoc()) {
        // Access value column and accumulate the values
        $value = $row['value_column'];
        $totalValue += $value;
        
        // You can also store values in an array if needed
        // $valuesArray[] = $value;
    }
    
    echo "Total value: $totalValue"; // Print total value
    // If you stored values in an array, you can print or manipulate the array here
    // print_r($valuesArray);
} else {
    echo "No records found.";
}

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

This PHP script fetches records from the database, accumulates the values from a specific column (value_column), and calculates the total value by adding up these values inside the while loop. After the loop, it prints the total value obtained. If you need to store these values in an array for further processing, you can uncomment and modify the $valuesArray[] = $value; line accordingly.

© 2025 Wavesdream Blog

Theme by Anders NorénUp ↑