welcome back to shortlearner.com, in this post we will see how to store data in cache file with the help of PHP.
before start this tutorial we should take an overview about cache.
so the very first question in our mind is what is cache , why we store our data in cache file, and what are the benefits to store data in this file.
so basically data caching refers to storing the result of an operation into a file so that future request return faster or we can say that caching is a perfect way to showing repeated data with minimum execution time.
in the below code we are creating a cache file with the help of php script and store data into that file and match the execution time of both actions.
$start = microtime(true);
$con = mysqli_connect("localhost","root","rootroot","testdb");
$cache_file = "cache/index.cache.php";
echo "data fetch from cache file";
echo "data not file";
$city = '';
$find = $con->query("SELECT * FROM cities");
$city .= $fetch['city'];
$handle =fopen($cache_file, 'w');
$end = microtime(true);
so i have a table in MySQL database with the name of cities and this table have thousands of record in it. so whenever i use select query to fetch all records from the database it takes some time to execution which is more than 5 seconds. i want to reduce this execution time from 5 seconds to 0.005 seconds.
here i am using microtime() which is store the time before the script is start for execution. than we declare a variable of $cache_file and check that the file is exist or not.
so in the very first time this is not exist so we fetch all records from database and store in our $cache_file by using predefined file functions.
now when we perform the same task again it will fetch records from our $cache_file file which will exist this time.
and after the end we store execution time again in our $end variable and than check the difference between start and end time of execution so we got the actual execution time of this script.