Can anyone tell me:
I have to upload the excel file and put all its data in database, but the condition is that if any of the records are existing already in the database i have to fire an update query. else fire an insert query for new records.
I am comparing the Roll No from database with Roll No from excel . It works fine with the existing data i.e It Updates all the existing . But it is not inserting the new data. Please check the code from :else if($num_rows>0)
Please Help Me.
Below is the code:
if($_FILES['excelFile']['name']!="")
{
$fileName=uploadFile($_FILES['excelFile'],array(".xls",".xlsx"),"excel_file");
$data = new Spreadsheet_Excel_Reader();
$data->read('excel_file/'.$fileName);
$ans=mysql_query("SELECT * FROM StudentData");
$num_rows = mysql_num_rows($ans);
for($i=1;$i<=$data->sheets[0]['numRows'];$i++)
{
$rollno=$data->sheets[0]['cells'][$i][1];
$firstname=$data->sheets[0]['cells'][$i][2];
$lastname=$data->sheets[0]['cells'][$i][3];
$mobile=$data->sheets[0]['cells'][$i][4];
$city=$data->sheets[0]['cells'][$i][5];
if($num_rows<=0)
{
echo('Inserting : '.$rollno);
$query="INSERT INTO StudentData(RollNo,FirstName,LastName,MobileNo,City)VALUES('".$rollno."','".$firstname."','".$lastname."','".$mobile."','".$city."')";
mysql_query($query);
}
else if($num_rows>0)
{
while($rows=mysql_fetch_array($ans))
{
if($rollno!=$rows['RollNo'])
{
echo('<p style="color:green">Inserting : '.$rollno.'</p>');
$query="INSERT INTO StudentData(RollNo,FirstName,LastName,MobileNo,City)VALUES('".$rollno."','".$firstname."','".$lastname."','".$mobile."','".$city."')";
mysql_query($query);
mysql_error();
break;
}
else
{
echo('<p style="color:red">Updating Roll:'.$rollno.'and DBR:'.$rows['RollNo'].'</p>');
$query="UPDATE StudentData SET FirstName='".$firstname."',LastName='".$lastname."',MobileNo='".$mobile."',City='".$city."' WHERE RollNo='".$rollno."'";
mysql_query($query);
break;
}
}
}
}
}
INSERT ... ON DUPLICATE KEY