Author: Sanjay Bhowmick (Page 4 of 4)

PHP function to get difference between dates

Below is a PHP function that calculates and displays the difference in days between two dates. This function will take two date strings as inputs, convert them to DateTime objects, and then calculate the difference in days.

Here’s how you can define and use the function:

<?php
// Calculate day difference
function calculateDayDifference($date1, $date2) {
    // Create DateTime objects for the two dates
    $datetime1 = new DateTime($date1);
    $datetime2 = new DateTime($date2);

    // Calculate the difference
    $interval = $datetime1->diff($datetime2);

    // Get the difference in days
    $days_interval = $interval->days;

    return  $days_interval;
}

// Example usage
$date1 = "2023-07-01";
$date2 = "2023-07-15";

echo calculateDayDifference($date1, $date2);
?>

Explanation:

Creating DateTime Objects:

new DateTime($date1): This converts the first date string into a DateTime object.

new DateTime($date2): This converts the second date string into a DateTime object.

Calculating the Difference:

$datetime1->diff($datetime2): This calculates the difference between the two DateTime objects. The result is a DateInterval object.

Getting the Difference in Days:

$interval->days: This retrieves the difference in days from the DateInterval object.

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 numbers, mt_rand() is generally preferred because it is based on the Mersenne Twister algorithm, which is faster and has a better distribution of numbers. Feel free to use either function depending on your requirements.

Websites to find free high resolution stock-images

We always prefer good, high quality stock-images for our websites, blogs, print designs and may be for some other graphical work. Getting good images always cost a lot. Alternatively there are some websites which offer free images called ‘Public Domain Images’. Public domain images are not covered by intellectual property (Creative Commons license) or copyrights which mean these can be used anywhere without any copyright issues.

Here are the few websites to get public domain stock-images.

Pixabay

All images and videos on Pixabay are released free of copyrights under Creative Commons CC0. You may download, modify, distribute, and use them royalty-free for anything you like, even in commercial applications. Attribution is not required.
URL: www.pixabay.com

Publicdomainarchive

You can get vintage and modern free photos from this website. It is a place to find inspiration and photography that you can re-use in your creative projects.
URL: www.publicdomainarchive.com

SplitShire

You can download high quality free stock photos without copyright, do whatever you want and they update everyday.
URL: www.splitshire.com

Gratisography

This website has a good collection of high-resolution photos of different categories like animals, nature, objects, people, urban.
URL: www.gratisography.com

Unsplash

Unsplash is the most leading place to get high-resolution stock photos. It is a community driven website so you can upload your photograph on this website too. Also, if you subscribe on their website then you will get 10 high-resolution photos on your email every 10 days.
URL: www.unsplash.com

New Old Stock

If you want vintage collection then New Old Stock website is the best place. The image qualities are the best of the industry standard.
URL: nos.twnsnd.co

Focusfitness

If you’re looking for health and fitness stock photos Focus Fitness has you covered. They provide high resolution photos in these categories: food and drinks, exercises, fitness, weight loss, diet, and yoga. All stock photos are free for personal and commercial use.
URL: www.focusfitness.net/stock-photos/

PikWizard

Pikwizard is a wonderful new stock photography website that has over 100,000 high-quality images, with 20,000 completely exclusive to the website. It features excellent images of people, which are sometimes hard to find on the best stock photography websites. There is also no attribution required.
URL: www.pikwizard.com

Other websites from where you can also get high-resolution stock photos completely free for commercial use:

Check this website as they have put a large collection: https://www.whoishostingthis.com/resources/free-stock-images/

5 websites to get icons completely free

As a web and application developer I need icons on my every project. Icons are copyrighted assets like images. I prefer to use kind of public domain graphics which are completely free for commercial purposes.

From where we can get completely free icons for web and graphic design?

Here are the 5 best websites to get icons for your graphic design projects.

Fontello

This is my 1st choice because of its large collection of fonts and customization options. At fontello you can get icons as a web fonts which is really great for web developers. They offer API for developers to integrate their application on any other web / mobile application.
URL: www.fontello.com | Plan: Free

Icomoon

Icomoon is another great resource for this with web fonts. You can generate SVG for each icon too. You can download lots of icons in different vector formats completely free.
URL: www.icomoon.io | Plan: Free + Paid

Iconmonstr

This website also has a huge collection of icons under different categories. All the icons are highly designed and they offer each icon to download in a pack. The good thing is each icon pack includes the files in different format — SVG, AI, PSD and PNG.
URL: www.iconmonstr.com | Plan: Free

Flaticon

Flaticon has the largest collection of vector icons online. It had a nice tool to select icon, edit icon size and colour. You must have to credit the authorship of their designs in your website/application if you download as free. This website also provides each design in different format — PNG, SVG, EPS, BASE 64, PSD.
URL: www.flaticon.com | Plan: Free + Paid

Iconfinder

I never forget to share Iconfinder which was all time favourite and may be million of people use this website still. The website can tell all its collection and does not need any review from me. Iconfinder has different licence policies for icons and supports different format to download.
URL: www.iconfinder.com | Plan: Free + Paid

Websiteplanet

This tool allows you to create favicons from pictures that are up to 5 MB from either JPG, PNG or GIF or even from a gallery!
URL: www.websiteplanet.com | Plan: Free

Convert Indian currency from numeric to words in PHP

To convert a numeric value to Indian currency format (words), you can use a custom function. Here’s an example of how you can achieve this:

This function convertToIndianCurrencyWords() converts a numeric value into its Indian currency format representation in words.

<?php
function convertToIndianCurrencyWords($number) {
    $ones = array(
        0 => '', 1 => 'One', 2 => 'Two', 3 => 'Three', 4 => 'Four',
        5 => 'Five', 6 => 'Six', 7 => 'Seven', 8 => 'Eight', 9 => 'Nine'
    );

    $teens = array(
        11 => 'Eleven', 12 => 'Twelve', 13 => 'Thirteen', 14 => 'Fourteen',
        15 => 'Fifteen', 16 => 'Sixteen', 17 => 'Seventeen', 18 => 'Eighteen',
        19 => 'Nineteen'
    );

    $tens = array(
        1 => 'Ten', 2 => 'Twenty', 3 => 'Thirty', 4 => 'Forty', 5 => 'Fifty',
        6 => 'Sixty', 7 => 'Seventy', 8 => 'Eighty', 9 => 'Ninety'
    );

    $hundreds = array(
        '', 'Hundred', 'Thousand', 'Lakh', 'Crore'
    );

    $words = array();

    if ($number < 0) {
        $words[] = 'Minus';
        $number = abs($number);
    }

    $numString = (string)$number;

    $numDigits = strlen($numString);
    $numChunks = ceil($numDigits / 2);
    $numChunkLen = $numDigits % 2 ?: 2;
    $numChunkPos = 0;

    for ($i = 0; $i < $numChunks; ++$i) {
        $numChunk = substr($numString, $numChunkPos, $numChunkLen);
        $numChunk = (int)$numChunk;

        if ($numChunk != 0) {
            $numChunkWords = array();

            if ($numChunk >= 10 && $numChunk <= 19) {
                $numChunkWords[] = $teens[$numChunk];
            } elseif ($numChunk >= 20) {
                $tensDigit = (int)($numChunk / 10);
                $numChunkWords[] = $tens[$tensDigit];

                $onesDigit = $numChunk % 10;
                if ($onesDigit != 0) {
                    $numChunkWords[] = $ones[$onesDigit];
                }
            } elseif ($numChunk != 0) {
                $numChunkWords[] = $ones[$numChunk];
            }

            if (!empty($numChunkWords)) {
                $words = array_merge($words, $numChunkWords);
                if ($numChunkPos > 0) {
                    $words[] = $hundreds[$i];
                }
            }
        }

        $numChunkPos += $numChunkLen;
        $numChunkLen = 2;
    }

    return implode(' ', $words);
}

$number = 123456789; // Example number
$words = convertToIndianCurrencyWords($number);

echo ucfirst($words) . ' Rupees Only'; // Output: Twelve Crore Thirty Four Lakh Fifty Six Thousand Seven Hundred Eighty Nine Rupees Only
?>

Adjust the code as needed for different ranges or specific formatting requirements. The example provided here is a basic implementation for Indian currency representation.

Covert all date data format from VARCHAR to DATE in any MySQL table

Converting varchar data to date format in MySQL involves several steps. Here’s a method to achieve this:

Assuming your varchar date column is named date_column and your table is named your_table, you can follow these steps:

  1. Add a New Date Column: First, add a new date column to your table.
    ALTER TABLE your_table ADD new_date_column DATE;
  2. Update New Date Column: Update the newly added date column using the STR_TO_DATE function to convert the varchar dates to date format.
    UPDATE your_table
    SET new_date_column = STR_TO_DATE(date_column, ‘your_date_format’);

    Replace ‘your_date_format’ with the format of the varchar dates in your column. For example, if your dates are in the format ‘YYYY-MM-DD’, use ‘%Y-%m-%d’.
  3. Drop Old Date Column: If you’re confident that the new date column contains the correct data, you can drop the old varchar date column.
    ALTER TABLE your_table DROP COLUMN date_column;
  4. Rename New Date Column: Finally, rename the new date column to the original column name.
    ALTER TABLE your_table CHANGE new_date_column date_column DATE;

Remember to take a backup of your data before making such changes to your database. Incorrectly manipulating your database structure can lead to data loss. If possible, it’s recommended to keep dates in the appropriate date or datetime format rather than varchar to avoid these kinds of issues.

Also, be aware that converting varchar data to date format directly in the database can be resource-intensive, especially if you have a large amount of data. It’s usually better to clean and format data before inserting it into the database in the correct format.

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_database_name";

// Create a new Spreadsheet object
$spreadsheet = new Spreadsheet();

// Fetch data from the database
$conn = new mysqli($servername, $username, $password, $dbname);

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

$sql = "SELECT * FROM your_table";
$result = $conn->query($sql);

// Set column headers
$spreadsheet->setActiveSheetIndex(0)
    ->setCellValue('A1', 'ID')
    ->setCellValue('B1', 'Name')
    ->setCellValue('C1', 'Email');

// Populate data
$row = 2; // Start from row 2
while ($row_data = $result->fetch_assoc()) {
    $spreadsheet->getActiveSheet()
        ->setCellValue('A' . $row, $row_data['id'])
        ->setCellValue('B' . $row, $row_data['name'])
        ->setCellValue('C' . $row, $row_data['email']);

    $row++;
}

// Rename worksheet
$spreadsheet->getActiveSheet()->setTitle('Sheet 1');

// Redirect output to a client's web browser (Excel2007)
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="exported_data.xlsx"');
header('Cache-Control: max-age=0');

$writer = new Xlsx($spreadsheet);
$writer->save('php://output');
exit;
?>

3. Note:

Replace your_table with the actual name of your database table. Ensure you have Composer installed and run composer require phpoffice/phpspreadsheet in your project directory to install PHPSpreadsheet. When you access export_excel.php, it will generate an Excel file with the data fetched from your MySQL database.

How to reverse date in PHP

To reverse the date from the format “yyyy-mm-dd” to “mm-dd-yyyy” in PHP, you can use the following script:

<?php
$date = "2023-07-04";

// Reversing the date format
$reversedDate = date("m-d-Y", strtotime($date));

echo "Original date: " . $date . "<br>";
echo "Reversed date: " . $reversedDate;
?>

In this script, the variable $date holds the original date in the “yyyy-mm-dd” format. The date() function is then used to convert and format the date. By passing the $date variable to strtotime(), it is converted to a Unix timestamp, which can be easily manipulated. The date() function then reformats the timestamp to the desired “mm-dd-yyyy” format. Finally, the original and reversed dates are printed on the screen.

Newer posts »

© 2025 Wavesdream Blog

Theme by Anders NorénUp ↑