How to Import Excel Data To MySQL Using PHP -
can tell me:
i have upload excel file , put data in database, condition if of records existing in database have fire update query. else fire insert query new records.
i comparing roll no database roll no excel . works fine existing data i.e updates existing . not inserting new data. please check code :else if($num_rows>0)
please me.
below 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 * 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 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 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."' rollno='".$rollno."'"; mysql_query($query); break; } } } } }
i tried putting existing roll's in array!
so made array existing rollno
while($rows=mysql_fetch_array($ans)) { $existing_rollno[]=$rows['rollno']; }
then used php function:-
if (in_array($rollno, $existing_rollno))
and worked wanted.
Comments
Post a Comment