get csv data in php

In our earlier article, we have provided the demo with code for UI Data Base using Google spread sheet as back-end to show user interactive HTML form. Whereas in this article, we use CSV file as database and php as link code to get the required data. We are giving the source code. The following is simple excel sheet / csv for list of fruits (file name: fruit.csv).

ITEM CODEDETAILSQTY (Nos)RATE (Usd)STOCK
124APPLE20300NEW
127LEMON4060OLD
123MANGO10500NEW
135BANANA30600OLD
148ORANGE1240NEW
111MANGO20150OLD
125APPLE7100OLD
131GRAPES1575NEW

Let the file may be n number of columns, but the php code will fetch the rows that matches the data. This very simple php code and light in weight. Here in the file, there are 5 columns namely, data(0), data(1), data(2), data(3) and data(4).

Now we have to search the fruits where the stock is old and rate is less than 250 usd. Please ensure that which column first to be searched and what to be checked then after. The stock =old is coming in 5th column (i.e data(4) and the rate is coming in 4th column (i.e data(3) of the fruit.csv file. Hence, let us say the $x = "OLD"; (it will bring all the old stocks) and then $y="250'; it will bring all the stocks having old and rate having 250.. When we put less than 250, it will bring all the stocks having old and rate being less than 250. The php code will be some what

PHP CODE (fruit.php)
<!--php $x="OLD"; $y="250"; $handle = fopen("fruit.csv","r")or die("file dont exist"); $output = ''; while (!feof($handle )){ $data = fgetcsv($handle,4096,","); if(($data[4] ==$x) && ($data[3] <$y)){ $output .= sprintf( "Fruit: %s; Quantity: %d Kgs; Rate:@ %dUSD/Kg (Code:%d; Stock:%s)<br-->", $data[1], $data[2], $data[3],$data[0],$data[4]); } } echo $output; fclose($handle); ?>

The result will be like:
Fruit:LEMON; Quantity: 40 Kgs; Rate: 60USD/Kg (Code:127; Stock:OLD)
Fruit:MANGO; Quantity: 20 Kgs; Rate: 150USD/Kg (Code:111; Stock:OLD)
Fruit:APPLE; Quantity: 7 Kgs; Rate: 100USD/Kg (Code:125; Stock:OLD)

No comments:

Click Here To add Comment

Post a Comment