I written script for the validation for the fields of csv file.I have done it successfully but if the conditions are false csv file is not importing in database.
Here is my code:
include('db.php');
if (isset($_POST['load']))
{
if ( isset($_FILES["file"]))
{
//if there was an error uploading the file
if ($_FILES["file"]["error"] > 0)
{
echo "File Not Selected <br />";
}
else
{
$file_name = $_FILES["file"]["name"];
if($_FILES["file"]["type"] != "text/csv")
{
die("This is not a CSV file.");
}
else
{
$location="C:\\xampp\\mysql\\data\\import\\";
move_uploaded_file($_FILES["file"]["tmp_name"], $location . $_FILES["file"]["name"]);
/* From Validation */
$handle = fopen($location . $_FILES["file"]["name"], 'r');
if ($handle)
{
//the top line is the field names`
$fields = fgetcsv($handle, 4096, ',');
//loop through one row at a time
$counter=0;
while (($data = fgetcsv($handle, 1000, '|')) !== FALSE)
{
$srno=$data[0];
$date=$data[1];
$mobno=$data[2];
$city=$data[3];
$state=$data[4];
$type=$data[5];
$telecaller=$data[6];
if(empty($srno)==true)
{
echo"there is an empty field for srno<br/>";
}
$filter="/^([012]?\d|3[01])-([Jj][Aa][Nn]|[Ff][Ee][bB]|[Mm][Aa][Rr]|[Aa][Pp][Rr]|[Mm][Aa][Yy]|[Jj][Uu][Nn]|[Jj][u]l|[aA][Uu][gG]|[Ss][eE][pP]|[oO][Cc]|[Nn][oO][Vv]|[Dd][Ee][Cc])-(19|20)\d\d$/";
if(!preg_match($filter,$date))
{
$counter++;
echo"Invalid Date Format in Row "."$counter"."<br/>";
}
if(empty($date)==true)
{
echo"there is an empty field for date<br/>";
}
if( !preg_match("/^[0-9]{10}/",$mobno) )
{
echo "Please enter a valid phone number<br/>";
}
if(empty($mobno)==true)
{
echo"there is an empty field for mobile no<br/>";
}
if(!preg_match("/^[a-zA-Z0-9]+$/",$city,$state) == 1)
{
echo"check your fields for state or city <br/>";
}
if(empty($city)==true)
{
echo"there is an empty field for City<br/>";
}
if(empty($state)==true)
{
echo"there is an empty field for State<br/>";
}
if(empty($type)==true)
{
echo"there is an empty field for Type<br/>";
}
$query="SELECT telecaller FROM import2 WHERE telecaller='$telecaller'";
$result2=mysql_query($query);
if(mysql_num_rows($result2)==0)
{
echo"Check list for telecallers";
}
if(!is_numeric($srno))
{
echo"All Sr.NO are only digital not contain any other number<br/>";
}
if(empty($telecaller)==true)
{
echo"there is an empty field for telecaller<br/>";
}
}
fclose($handle);
}
$q="LOAD DATA INFILE '$file_name' IGNORE INTO TABLE import
FIELDS TERMINATED BY '|'
LINES TERMINATED BY '\n'
IGNORE 1 LINES
(srno,@date,@mobno,@city,@state,@type,@telecaller)
SET srno=srno,date=@date,mobno=@mobno,city=@city,
state=@state,type=@type,telecaller=@telecaller";
mysql_query($q) or die(mysql_error());
echo"File Uploaded and Updated Successfully";
mysql_query("INSERT INTO temp1 SELECT mobno,telecaller FROM import GROUP BY mobno HAVING COUNT(*)>1 ") or die(mysql_error());
mysql_query("UPDATE import,temp1 SET import.telecaller=temp1.telecaller WHERE import.mobno=temp1.mobno");
} }
}