Posts

Showing posts from 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 strea...

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 $va...

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: Ensure you have a MySQL database and table set up to store the CSV data. 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($servern...