Reputation: 123
I do an upload form for user to upload csv file. Data in csv will be imported to database. Data will be import to database if no error occur. But sometimes there is mismatch of data with column data type. Example column data type is "int", data in csv is "varchar". How can i know which cell have error and tell user?
Untill now, i just do an error message "There is format error in the csv file" if csv file unsuccessfully imported.
if(isset($_POST["Import"])){
echo $filename=$_FILES["file"]["tmp_name"];
if($_FILES["file"]["size"] > 0){
$file = fopen($filename, "r");
while(($emapData = fgetcsv($file, 10000, ",")) !== FALSE){
$sql = "INSERT INTO Diary(id, date, remarks, status) VALUES('$emapData[0]','$emapData[1]','$emapData[2]','$emapData[3]')";
if($sql==0){
echo " There is format error in the csv file ";
}
$res=$dbcon->query($sql);
}
fclose($file);
echo "CSV File has been succesfully Imported";
}
else
echo 'Invalid File:Please Upload CSV File';}
Upvotes: 0
Views: 93
Reputation: 68
All you need to do is find the current row and column, and check data type of each column.
I prefer to create a function array to do check by column.
$checkColType = array(
#### col => function($val){ return 'error msg'; }
0 => function( $val ){
if( some statement ){ return 'Is not an id'; }
},
1 => function( $val ){
if( some statement ){ return 'Is not a date'; }
},
2 => etc...
);
$row = 0;
while(($emapData = fgetcsv($file, 10000, ",")) !== FALSE){
$CurrentRow = $row+1;
$ErrorMsg = '';
#### Do Check, and return Error
foreach( $checkColType as $col => $ColTypeFns ){
$CurrentCol = $col+1;
$Error = $ColTypeFns( $emapData[ $col ] );
if( $Error ){
$ErrorMsg.= "Cell $CurrentRow-$CurrentCol: $Error";
}
}
if( $ErrorMsg ){ echo "$ErrorMsg"; }
else{
#### Do Something...
}
$row++;
}
Upvotes: 0
Reputation: 669
Why don't you validate values before insert values into database
if(is_numeric($emapData[0]) && is_numeric($emapData[1]) ....)
{
$sql = "INSERT INTO Plant_Diary(plant_core_id, date_diary, remarks, plant_status) VALUES('$emapData[0]','$emapData[1]','$emapData[2]','$emapData[3]')";
}
else{
echo 'error data type';
}
Upvotes: 1