Skip to main content

Posts

Showing posts from February, 2024

Export MySQL data into Excel using PHP

To fetch data from a MySQL database and export it to Excel, you can use PHP along with a library like PHPExcel or PHPSpreadsheet (which is the successor of PHPExcel). Here, I'll provide an example using PHPExcel. Please note that PHPExcel is now deprecated, and PHPSpreadsheet is recommended for new projects. If you're starting a new project, consider using PHPSpreadsheet. However, if you need to work with PHPExcel for any reason, you can still find it on GitHub ( https://github.com/PHPOffice/PHPExcel ). 1. Install PHPSpreadsheet: You can install PHPSpreadsheet using Composer: composer require phpoffice/phpspreadsheet 2. Create a PHP Script (export_excel.php): <?php require 'vendor/autoload.php' ; use PhpOffice\PhpSpreadsheet\Spreadsheet; use PhpOffice\PhpSpreadsheet\Writer\Xlsx; // Database connection details $servername = "localhost" ; $username = "your_username" ; $password = "your_password" ; $dbname = "your_data

Generate random number in PHP

In PHP, you can generate a random number between 1 and 9 using the rand() or mt_rand() functions. Here are examples of both: Using rand() Function: $randomNumber = rand(1, 9); echo "Random number between 1 and 9: " . $randomNumber; Using mt_rand() Function: $randomNumber = mt_rand(1, 9); echo "Random number between 1 and 9: " . $randomNumber; Both functions will generate a random integer between the specified range, inclusive of both 1 and 9. Here’s how you might use this in a simple PHP script: <?php // Generate a random number between 1 and 9 using rand() $randomNumberRand = rand( 1 , 9 ); echo "Random number using rand(): " . $randomNumberRand . "<br>" ; // Generate a random number between 1 and 9 using mt_rand() $randomNumberMtRand = mt_rand( 1 , 9 ); echo "Random number using mt_rand(): " . $randomNumberMtRand ; ?> Why Use mt_rand()?  While both rand() and mt_rand() are suitable for generating random

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 . '"