Friday, 3 June 2016

How To Import CSV File Data Into Mysql Using PHP

How to Import CSV File Data Into Mysql


If you are a developer then definitely you might have faced this. Many times you  need to import data from a CSV (comma separated value) file and insert it into your MySQL database.


Say for Example consider a case when you have many records in a CSV file and you need to import them into your MySQL database then you can’t  insert each n every single record manually as it will take too much time.


This case arises mostly when you want to import existing data in your website. In this tutorial I am going to  explain you how easily you can do that.

 Note : Many users had problem with previous script because of the incorrect file type or incorrect file data. So here I have updated the script for the easy understanding and performance improvement. I have attached some snaps for better understanding. If you have too many records, then you should increase the max_execution_time in php.ini file before running this script.


Case 1 : 




In this example, I assume that you have the correct columns data in your .csv file. In above case the ID represents the ID's of other table data (that might be exported). In this case these ID's values will be added in the table.


Case 2 :





As you can see in the above case, if your csv file hasn't ID column, then don't include it as blank. Simply remove it and keep only other fields(columns). In this case, table's auto_increment ID values will be added.


Case 3 :  Your .csv file must have correct data and first row as header(fields title).



Usage Notes: If your .csv file hasn't ID column, then just remove the "ID" from the INSERT query and remove last one column value(change this as per your file columns).

$col3   = $col[2];
$query = "INSERT INTO csvtbl(name,city) VALUES('".$col1."','".$col2."')";



This Updated Script will solve the previous issues of getting repeated (three times) values, skipping first row etc,. just make sure that you have followed the above cases correctly.


SQL query to create csvdata table:

CREATE TABLE IF NOT EXISTS `csvtbl`(
 `ID` int(10) NOT NULL AUTO_INCREMENT,
 `name` varchar(50) NOT NULL,
 `city` varchar(50) NOT NULL,
 PRIMARY KEY (`ID`) )


csvimport.php File

<?php

//database connection details
$connect = mysql_connect('localhost','root','123456');

if (!$connect) {
 die('Could not connect to MySQL: ' . mysql_error());
}

//your database name
$cid =mysql_select_db('test',$connect);

// path where your CSV file is located
define('CSV_PATH','C:/wamp/www/');

// Name of your CSV file
$csv_file = CSV_PATH . "test.csv"; 


if (($handle = fopen($csv_file, "r")) !== FALSE) {
   fgetcsv($handle);   
   while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
        $num = count($data);
        for ($c=0; $c < $num; $c++) {
          $col[$c] = $data[$c];
        }

 $col1 = $col[0];
 $col2 = $col[1];
 $col3 = $col[2];
   
// SQL Query to insert data into DataBase
$query = "INSERT INTO csvtbl(ID,name,city) VALUES('".$col1."','".$col2."','".$col3."')";
$s     = mysql_query($query, $connect );
 }
    fclose($handle);
}

echo "File data successfully imported to database!!";
mysql_close($connect);
?>

Date Validation In PHP

In this post we will see how to validate date in PHP. Date that you want to test may have various Formats Like…

=> YYYY-MM-DD
=> DD/MM/YYYY
=> MM-DD-YYYY
=> DD-MM-YYYY
=> YYYY-MM-DD and so on..

We will see mostly used formats. Date in the other format  can easily be validated by making small changes in the existing code. So, let’s have look at them.

YYYY-MM-DD Format

$date = '2013-05-14';
//Date that needs to be tested goes here

 function isItValidDate($date) {
 if(preg_match("/^(\d{4})-(\d{2})-(\d{2})$/", $date, $matches))  
  {
   if(checkdate($matches[2], $matches[3], $matches[1]))
    { 
     return true;
    }
  }
 } 

if(isItValidDate($date))
 {
   echo 'It’s a valid Date. '; 
 } 
 else
 {
  echo 'Entered Date is invalid..!!'; 
 }

DD/MM/YYYY Format

$date = '14/05/2013'; 
//Date that needs to be tested goes here  

function isItValidDate($date) {
  if(preg_match("/^(\d{2})\/(\d{2})\/(\d{4})$/", $date, $matches))
   {
    if(checkdate($matches[2], $matches[1], $matches[3]))
      {
       return true; 
      }
   }
 }

if(isItValidDate($date))
 {
  echo 'It’s a valid Date';
 }
 else
 {
 echo 'Entered Date is invalid..!!';
 }

MM-DD-YYYY Format

$date = '05-14-2013'; 
//Date that needs to be tested goes here

function isItValidDate($date) {
 if(preg_match("/^(\d{2})-(\d{2})-(\d{4})$/", $date, $matches)) 
  {
  if(checkdate($matches[1], $matches[2], $matches[3]))
   {
    return true;
   }
  }
 }

if(isItValidDate($date)) 
{
 echo 'It’s a valid Date'; 
}
 else
 {
  echo 'Entered Date is invalid..!!';
 }

PHP checkdate function

checkdate

(PHP 4, PHP 5, PHP 7)
checkdate  Validate a Gregorian date

Description 

bool checkdate ( int $month , int $day , int $year )
Checks the validity of the date formed by the arguments. A date is considered valid if each parameter is properly defined.

Parameters 

month
The month is between 1 and 12 inclusive.
day
The day is within the allowed number of days for the given month. Leap years are taken into consideration.
year
The year is between 1 and 32767 inclusive.

Return Values 

Returns TRUE if the date given is valid; otherwise returns FALSE.

Examples 

Example #1 checkdate() example
<?php
var_dump
(checkdate(12312000));var_dump(checkdate(2292001));?>
The above example will output:
bool(true)
bool(false)

PHP Date functions

Displaying Present Month

echo date('M');
The output is here.
Jun

Displaying Last Month

echo date('M',strtotime("first day of last month"));
May

Displaying 2nd Last Month

echo date('M',strtotime("last day of -2 month"));
Apr

Present Day of the Week

echo date('l');
The output is here.
Friday

Present Day of the Month

echo date('d');
The output is here.
03

PHP Month year day selection drop down list to generate date format

<?Php
$todo=$_POST['todo'];
if(isset($todo) and $todo=="submit"){
$month=$_POST['month'];
$dt=$_POST['dt'];
$year=$_POST['year'];
$date_value="$month/$dt/$year";
echo "mm/dd/yyyy format :$date_value<br>";
$date_value="$year-$month-$dt";
echo "YYYY-mm-dd format :$date_value<br>";
}

?>
<form method=post name=f1 action=''><input type=hidden name=todo value=submit>
<table border="0" cellspacing="0" >
<tr><td align=left >
<select name=month value=''>Select Month</option> <option value='01'>January</option> <option value='02'>February</option> <option value='03'>March</option> <option value='04'>April</option> <option value='05'>May</option> <option value='06'>June</option> <option value='07'>July</option> <option value='08'>August</option> <option value='09'>September</option> <option value='10'>October</option> <option value='11'>November</option> <option value='12'>December</option> </select>

</td><td align=left >
Date<select name=dt >
<option value='01'>01</option> <option value='02'>02</option> <option value='03'>03</option> <option value='04'>04</option> <option value='05'>05</option> <option value='06'>06</option> <option value='07'>07</option> <option value='08'>08</option> <option value='09'>09</option> <option value='10'>10</option> <option value='11'>11</option> <option value='12'>12</option> <option value='13'>13</option> <option value='14'>14</option> <option value='15'>15</option> <option value='16'>16</option> <option value='17'>17</option> <option value='18'>18</option> <option value='19'>19</option> <option value='20'>20</option> <option value='21'>21</option> <option value='22'>22</option> <option value='23'>23</option> <option value='24'>24</option> <option value='25'>25</option> <option value='26'>26</option> <option value='27'>27</option> <option value='28'>28</option> <option value='29'>29</option> <option value='30'>30</option> <option value='31'>31</option> </select>
</td><td align=left > Year(yyyy)<input type=text name=year size=4 value=2005> <input type=submit value=Submit> </table> </form>

Tested in June month
for($i=0;$i<=11;$i++){
$month=date('M',strtotime("first day of -$i month")); // Month name with 3 letters
echo $month ."<br>";
}
?>
Output is here
Jun
May
Apr
Mar
Feb
Jan
Dec
Nov
Oct
Sep
Aug
Jul
<?php
echo "<select name=month>";
for($i=0;$i<=11;$i++){
$month=date('F',strtotime("first day of -$i month")); // Month full name
echo "<option value=$month>$month</option> ";
}
echo "</select>";
?>

June
May
April
March
February
January
December
November
October
September
August
July

<?php
//Listing next 5 years starting from present year
echo "<select name=year>";
for($i=0;$i<=5;$i++){
$year=date('Y',strtotime("last day of +$i year"));
echo "<option name='$year'>$year</option>";
}
echo "</select>";
?>

PHP Display next 10 months and past 10 months including this month with year

<?php
for ($i=0; $i<10; $i++)
{
    $timestamp = mktime(0,0,1,date("m")+$i,date("d"),date("Y"));
    $month = date("F Y", $timestamp);
    echo "{$month}<br />\n";

?>

For Past 10 months including this month
Filter by month:<select name="month">
<option value="?month=">All months</option>
<?php
$beginning_month = 10;
for($x=0;$x<$beginning_month;$x++){

    $time = strtotime("$x months ago");
    $month = date("F Y",$time);
    $link = strtolower(date("MY",$time));
   
    if(isset($_GET['month']) && $link == $_GET['month']) {
        
        echo '<option value="'.$link.'" selected="selected">'.$month.'</month>';
   
    } else {
    echo '<option value="'.$link.'">'.$month.'</month>';
    }
}

echo '</select>';
echo '<input type="submit" value="Filter" />'; 
?>


PHP Month full names dropdown

<?php
$monthArray = range(1, 12);
?>
<select name="month">
    <option value="">Select Month</option>
 <?php  
    foreach ($monthArray as $month) {
        // padding the month with extra zero
        $monthPadding = str_pad($month, 2, "0", STR_PAD_LEFT);
        // you can use whatever year you want
        // you can use 'M' or 'F' as per your month formatting preference
        $fdate = date("F", strtotime("2015-$monthPadding-01"));
        echo '<option value="'.$monthPadding.'">'.$fdate.'</option>';
    }
?>  
</select>