i am importing a huge data from a csv file into my database, but the issue is , if there is a error in the sql , my insertion stops , thus making my bulk insertion useless.i have to go back , delete the uploaded data and remove that entry which is causing issue in my insertion and start again . i want programme to skip it and continue insertion, i know i have to apply try and catch, i have applied it in my algo but i cnt understand how to use so that it continues its insertion . here is my code
$num=35; //number of columns
$dum=true; // a check
$sum=0;// count total entries
if (($handle = fopen($_FILES['file']['name'], 'r')) !== FALSE) {
while (($data = fgetcsv($handle, 10000, ',')) !== FALSE)
{
if($dum)
{
for ($qwe=0; $qwe < $num; $qwe++) { //searching the columns exact position in case they have been changed
if($data[$qwe]=='ID')
{$a=$qwe;}
.
.
.
.
.else if($data[$qwe]=='PowerMeterSerial')
{$aa=$qwe;}
else if($data[$qwe]=='Region')
{$ab=$qwe;}
else if($data[$qwe]=='Questions')
{$ac=$qwe;}
}
}
if(!$dum)
{
for($qwe=0;$qwe<$num;$qwe++)
{
if($qwe==7||$qwe==8)
{
if($qwe==7){$asd=$data[$qwe];}
$data[$qwe]=date('Y-m-d h-i-s',strtotime($data[$qwe]));
}
}
$data[57]=date('Y-m-d ',strtotime($asd));try {
$sql="INSERT I开发者_开发知识库NTO pm (ID, .......... Questions, dateofdata ,Unsuccessful) VALUES ('$data[$a]','$data[$b]','$data[$c]','$data[$d]','$data[$e]','$data[$f]','$data[$g]','$data[$h]' ,'$data[$i]','$data[$j]','$data[$k]', '$data[$l]', '$data[$m]','$data[$n]','$data[$o]','$data[$p]','$data[$q]','$data[$r]','$data[$s]','$data[$t]','$data[$u]','$data[$v]','$data[$w]', '$data[$x]','$data[$y]','$data[$z]','$data[$aa]','$data[$ab]','$data[$ac]','$data[57]','$data[30]')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error(). $sql);
}
}
catch (Exception $e)
{
echo'<br>'; echo $sql;
}
$sum++;
}$dum=false;
}
}
?>
kindly note there is no issue in uploading algorithme or sql , its when input data does not match the data type than sql generates a error , for that i am trying try and catch .. please help
Change your die()
command to a print()
. You'll see what the error was, and the script will move on to the next line.
Given the structure of your code, I'm guessing it'll blow up anytime you're inserting a string (particularly with quotes inside it), causing SQL syntax errors. You MUST pass each text field from your csv through mysql_real_escape_string()
BEFORE you insert those values into the query string.
精彩评论