How to count the uploaded data's through .csv in php - php

I have a php code to upload a .csv file this one is working fine. But what i want is if i upload 10 records in a .csv file means it display how many records i upload and in that how many is correctly and how many's are wrong.
Here is my code :
if (isset($_POST["submitbutton"])) {
if (!empty($_FILES['file']['name'])) {
if (pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION) == 'csv') {
$handle = fopen($_FILES['file']['tmp_name'], "r");
//Grab the header in csv
$headers = fgetcsv($handle, 1000, ",");
$not_valid = [];
$i = 1;
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$aValid = false;
$field1 = mysql_real_escape_string($data[0]);
$field2 = mysql_real_escape_string($data[1]);
$field3 = mysql_real_escape_string($data[2]);
$field4 = mysql_real_escape_string($data[3]);
$field5 = mysql_real_escape_string($data[4]);
$field6 = mysql_real_escape_string($data[5]);
$field7 = mysql_real_escape_string($data[6]);
$field8 = mysql_real_escape_string($data[7]);
$field9 = mysql_real_escape_string($data[8]);
$sql2 = "select * from m_tl_mastercourse where LMS_Course_ID='$field9'";
$check1 = mysql_query($sql2);
$sql = "select * from mdl_course where id='".$field9."'";
$check = mysql_query($sql);
$row=mysql_fetch_array($check);
if (mysql_num_rows($check) > 0 && mysql_num_rows($check1) < 1) {
$aValid = true;
} else {
$not_valid[] = $i;
}
if ($aValid) {
echo count($i);
$import = "INSERT into m_tl_mastercourse values('','$field1','$field2','$field3','$field4','$field5','$field6','$field7','$field8','$field9')";
mysql_query($import);
$last_id = mysql_insert_id();
if($last_id){
$sql = "select m_tl_mastercourse.Id, Course_Type from m_tl_mastercourse inner join mdl_course where m_tl_mastercourse.LMS_Course_ID = mdl_course.id ";
$ret = get_records_sql($sql);
foreach ($ret as $index => $obj) {
$master_id = $obj->Id;
$course_type = $obj->Course_Type;
}
echo $master_id;
echo $course_type;
$query = mysql_query("update m_tl_course INNER JOIN m_tl_mastercourse ON m_tl_course.course_id = m_tl_mastercourse.LMS_Course_ID SET m_tl_course.course_type='$course_type',m_tl_course.master_id='$master_id' WHERE m_tl_course.master_id='' ");
}
}
$i++;
}
fclose($handle);
if (!empty($not_valid)) {
$v_ids = implode(', ', $not_valid);
echo count($v_ids);
echo "Please check the following csv Row Number's - " . $v_ids;
} else {
echo "Master Courses Uploaded Successfully";
}
} else {
echo "<script>alert('csv files only allowed to upload')</script>";
}
} else {
echo "<script>alert('Please select a file')</script>";
}
}
?>
How to get like this

The variables are already in your code: $i is incremented on each loop, and $not_valid is an array containing the row numbers for any rows that are evaluated as not valid.
You can use count($not_valid) to get the number.
// $i starts at 1 and is incremented on the completion of each loop so will end 1 more than the total rows
$total_rows = $i - 1;
$valid_rows = $i - 1 - count($not_valid);
$invalid_rows = count($not_valid);

Related

php problems with union select distinct

I submitted these two files:
sample_annotation.txt
sample_synteny.txt
I got on the next page the following error:
304501820180500000018.304501820180500000018<br><br>select distinct org1,org2 from '.304501820180500000018.'_synteny union select distinct org1,org2 from '.304501820180500000018.'_synteny<br><br>
Invalid query: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''.304501820180500000018.'_synteny union select distinct org1,org2 from '.3045018' at line 1
Whole query: select distinct org1,org2 from '.304501820180500000018.'_synteny union select distinct org1,org2 from '.304501820180500000018.'_synteny[]
The mGSV/lib/data.php looks like below and caused the above error:
<?php
include('database.php');
## Get parameters
$org = $_GET['org'];
$data = $_GET['data'];
$session_id = $_GET['session_id'];
$array = array();
if($data == 'annotation') {
$query = "SELECT track_name FROM ".$session_id."_annotation WHERE org_id like '$org' GROUP BY track_name ";
$result = mysql_query($query);
if($result != ''){
while($row = mysql_fetch_assoc($result)){
array_push($array, $row['track_name']);
}
}
//array_push($syn_array, "10_50_20_70");
}
else if ($data == 'synteny') {
$query = "DESC ".$session_id."_synteny";
$result = mysql_query($query);
while($row = mysql_fetch_assoc($result)){
if($row['Field'] == 'id'){ continue; }
if($row['Field'] == 'blocks'){ continue; }
if($row['Field'] == 'SYNcolor'){ continue; }
if(! preg_match("/^org[12]+[_]?[start|end]?/", $row['Field'])){
array_push($array, $row['Field']);
}
}
}
else if ($data == 'size'){
echo "$session_id.", $session_id, "<br>";
echo "$org", $org, "<br>";
$query = "select distinct org1,org2 from '.$session_id.'_synteny union select distinct org1,org2 from '.$session_id.'_synteny";
echo $query,"<br>";
$result = mysql_query($query);
echo $results,"<br>";
if ($results) {
while($row = mysql_fetch_assoc($result)){
echo $row['org1'], "<br>";
$q = "select max(output) as max from (select max(greatest(org1_start, org1_end)) as output from ".$session_id."_synteny where org1 like '" . $row['org1'] . "' union select max(greatest(org2_start, org2_end)) as output from ".$session_id."_synteny where org2 like '" . $row['org1'] . "') as t1";
echo $q, "<br>";
$res = mysql_query($q);
if (!$res) {
die('Could not query:' . mysql_error());
}
echo $row['org1'],"<br>";
echo $row['org2'],"<br>";
if (! isset($array[$row['org1']])){
//echo "add<br>";
$array[$row['org1']] = mysql_result($res,0);
}
$q = "select max(output) as max from (select max(greatest(org1_start, org1_end)) as output from ".$session_id."_synteny where org1 like '" . $row['org2'] . "' union select max(greatest(org2_start, org2_end)) as output from ".$session_id."_synteny where org2 like '" . $row['org2'] . "') as t1";
#echo $q, "<br>";
$res = mysql_query($q);
if (!$res) {
die('Could not query:' . mysql_error());
}
if (! isset($array[$row['org2']])){
//echo "add<br>";
$array[$row['org2']] = mysql_result($res,0);
}
}
}
else {
echo 'Invalid query: ' . mysql_error() . "\n";
echo 'Whole query: ' . $query;
}
}
else if ($data == 'order'){
$query = "select distinct org1 from ".$session_id."_synteny union select distinct org2 from ".$session_id."_synteny ";
//echo $query,"<br>";
$result = mysql_query($query);
$default = array();
while($row = mysql_fetch_assoc($result)){
array_push($default, $row['org1']);
}
$array = join('__ORDER__', $default);
}
else if ($data == 'sorder'){
$query = "select distinct org1,org2 from ".$session_id."_synteny union select distinct org1,org2 from ".$session_id."_synteny ";
//echo $query,"<br>";
$result = mysql_query($query);
$default = array();
$assarr = array();
while($row = mysql_fetch_assoc($result)){
if( ! in_array($row['org1'], $default)){
array_push($default, $row['org1']);
$assarr[sizeof($assarr)] = array();
}
if( ! in_array($row['org2'], $default)){
array_push($default, $row['org2']);
$assarr[sizeof($assarr)] = array();
}
$len_query = "select sum(org1_end) - sum(org1_start) + sum(org2_end) - sum(org1_start) as sum from ".$session_id."_synteny where (org1 like '".$row['org1']."' and org2 like '".$row['org2']."') OR (org1 like '".$row['org2']."' and org2 like '".$row['org1']."')";
$q_result = mysql_query($len_query);
$q_row = mysql_fetch_assoc($q_result);
#echo $len_query,"<br>";
#echo $q_row['sum'],"<br>";
$assarr[array_search($row['org1'], $default)][array_search($row['org2'], $default)] = $q_row['sum'];
#$assarr[array_search($row['org1'], $default)][array_search($row['org2'], $default)] = 1;
$assarr[array_search($row['org2'], $default)][array_search($row['org1'], $default)] = $q_row['sum'];
#$assarr[array_search($row['org2'], $default)][array_search($row['org1'], $default)] = 1;
#echo array_search($row['org1'], $default) . "][ ". array_search($row['org2'], $default) . '<br>';
$assarr[array_search($row['org1'], $default)][array_search($row['org1'], $default)] = 0;
#echo array_search($row['org1'], $default) . "][ ". array_search($row['org1'], $default) . '<br>';
$assarr[array_search($row['org2'], $default)][array_search($row['org2'], $default)] = 0;
#echo array_search($row['org2'], $default) . "][ ". array_search($row['org2'], $default) . '<br>';
}
$a = FindOrder($assarr);
$sugg = array();
//echo sizeof($a),'<br>';
foreach($a as $b){
//echo $default[$b],"<br>";
array_push($sugg, $default[$b]);
}
$array = join('__ORDER__', $sugg);
}
function FindOrder($graph){
$r = array();
$last = -1;
while(!isEmpty($graph)){
$start = leastEdges($graph);
$path = longestPath($graph, $start, 0);
$path = completeCycle($graph, $path);
if($path[0] != $last){
array_push($r, $path[0]);
}
for($x = 1; $x < sizeof($path); $x++){
array_push($r, $path[$x]);
}
$last = $path[sizeof($path)-1];
$graph = removePath($graph, $path);
}
return $r;
}
function longestPath($graph, $cur, $len){
$path = array();
array_push($path, $cur);
$longestSubpath = array();
for($x = 0; $x < sizeof($graph); $x++){
if($graph[$cur][$x] != 0){
$subpath = longestPath(removeVertex($graph, $cur), $x, $len + $graph[$cur][$x]);
if(sizeof($subpath) > sizeof($longestSubpath)){
$longestSubpath = $subpath;
}
}
}
foreach($longestSubpath as $x){
array_push($path, $x);
}
return $path;
}
function completeCycle($graph, $path){
$graph = removePath($graph, $path);
$last = $path[sizeof($path)-1];
for($x = 0; $x < sizeof($graph); $x++){
if($graph[$last][$x] != 0){
array_push($path, $x);
return $path;
}
}
return $path;
}
function removePath($graph, $path){
for($x = 0; $x < sizeof($path) - 1; $x++){
$arr = $path[$x]; //***forgot the $ in front of path***
$b = $path[$x+1]; //***forgot the $ in front of path***
$graph[$arr][$b] = 0;
$graph[$b][$arr] = 0;
}
return $graph;
}
function removeVertex($graph, $vtx){
if($vtx < 0 || $vtx >= sizeof($graph)){
return copy($graph);
}
for($x = 0; $x < sizeof($graph); $x++){
$graph[$x][$vtx] = 0;
$graph[$vtx][$x] = 0;
}
return $graph;
}
function numEdges($vtx){
$r = 0;
foreach($vtx as $x){
if($x != 0){
$r++;
}
}
return $r;
}
function leastEdges($graph){
$r = -1;
$min = 2147483647;
for($x = 0; $x < sizeof($graph); $x++){
$e = numEdges($graph[$x]);
if($e != 0 && $e < $min){
$r = $x;
$min = $e;
}
}
return $r;
}
function isEmpty($arr){
$r = true;
foreach($arr as $x){
$r = $r && numEdges($x) == 0;
}
return $r;
}
## Return the JSON object
echo json_encode($array);
?>
I created a docker-compose.yml and the can be run in the following way:
git clone https://github.com/mictadlo/mGSV-docker.git
docker-compose up --build
The service can be accessed via localhost and PhpMyAdmin can be accessed via localhost:8183
What did I miss?
Thank you in advance
Try to run independently both query in your Mysql phpmyadmin
select distinct org1,org2 from '.304342020180200000016.'_synteny
select distinct org1,org2 from '.304342020180200000016.'_synteny
As i see your query seems to be correct since union requires the same numbers of columns and same data type.
And why is your table name in the union query is both the same.

Query Debugging.

I have two tables i am using two quires to fetch data from them separately.
$query = mysql_query("SELECT * FROM offers");
$query1 = mysql_query("SELECT * FROM Offers_Dalia ") or die(mysql_error());
I am printing the result on one html-table.
.... the problem is that i want to know that why the loop is running for 11 times both.
1). I am using two while loops. 2). each loop is running for row->mysql_fetch_object times. please help me to find error why my both loops are running for 11 times. total 22 rows are present in html table output. but my both table have so many rows. 100 of rows in both table.
please check the code.
$query = mysql_query("SELECT * FROM offers");
$query1 = mysql_query("SELECT * FROM Offers_Dalia ") or die(mysql_error());
$x = 1;
$n = 0;
while($row = mysql_fetch_object($query))
{
$oid = $row->id;
$name = stripslashes($row->name);
$reward = stripslashes($row->credits);
$network = stripslashes($row->network);
$hits = $row->hits; //clicks; $epc = $row->epc;
$campid = stripslashes($row->campaign_id);
$country = $row->countries;
$url2=$row->link;
$desc=$row->description;
if($x%2 == 0)
{
$trColor = "f1f0f0";
}else
{
$trColor = "ffffff";
}
if(stristr($country, ","))
{
$country_arrs = explode(",", $country);
$country = implode(", ", $country_arrs);
}
?>
<tr style="background:#<?=$trColor?>" ><td><input type="checkbox" value="<?=$oid?>" name="ids[]" onclick="uncheckCheckAllbox(this)" /></td><td><?=$campid?>- campId</td><td><?=$name?></td><td><?=$reward?><td><?=$network?><td><?=$desc?></td><td>Click Here</td></td><td><?=$country?></td></tr>
$n++;
while($row1 = mysql_fetch_object($query1))
{
$uuid = $row1->offers_uuid;
$title1 = stripslashes($row1->title);
$info1 = stripslashes($row1->info_short);
$device_kind1 = stripslashes($row1->device_kinds);
$country1 = stripslashes($row1->target_groups_values);
// $status = toggleStatus($row->active);
$reward_dollar1 = $row1->reward_dollar; //clicks;
$url1 = $row1->url;
$network1 = 'Dalia';
$url1 = urldecode($url1);
if($x%2 == 0)
{
$trColor = "f1f0f0";
}else
{
$trColor = "ffffff";
}
if(stristr($country, ","))
{
$country_arrs = explode(",", $country);
$country = implode(", ", $country_arrs);
}
?>
<tr style="background:#<?=$trColor?>" ><td><input type="checkbox" value="" onclick="uncheckCheckAllbox(this)" /></td><td><?=$uuid?></td><td><?=$title1?></td><td><?=$reward_dollar1?></td><td><?=$network1?></td><td><?=$info1?></td><td>Click Here</td><td><?=$country1?></td></tr>
$n++;
$x++;
goto n;
}
n:
$x++;
}

Premature end of script headers: php-cgi and internal server error

need some helps here: i try to import some excel sheets to my website, but the page keep loading and then stop working and showing internal server error text. the error log shows this caused by the import.php :Premature end of script headers: php-cgi, referer: ...file_import.php.
below are the codes:
<? include("../include/begin.inc.php");?>
<?
function showerror()
{
die("Error " . mysql_errno() . " : " . mysql_error());
}
function sava_data($array, $table){
$count = 0;
$total = 0;
foreach( $array as $tmp){
if ($count <> 0){
$date = date("Y:m:d H:i:s");
$sql = "INSERT INTO $table set ";
$sql .= "detail = '{$tmp[2]}', shape = '{$tmp[3]}', qty = '{$tmp[4]}', price = '{$tmp[5]}', percent = '{$tmp[6]}', colour = '{$tmp[7]}', clarity = '{$tmp[8]}', prop = '{$tmp[9]}', polish = '{$tmp[10]}', smy = '{$tmp[11]}', diam = '{$tmp[12]}', t_dep = '{$tmp[13]}', `table` = '{$tmp[14]}', fl = '{$tmp[15]}', colour_shade = '{$tmp[16]}', cert = '{$tmp[17]}', cert_no = '{$tmp[18]}', per_kg = '{$tmp[19]}', selling_price = '{$tmp[20]}', status = 'new', create_date = '{$date}'";
//echo $sql."<br>";
//exit();
if (!($result = #mysql_query($sql) or die("Error:" . mysql_error().$sql)))
showerror();
$total++;
}
$count++;
}
return $total;
}
function save_data2($array,$table){
$count = 0;
$total = 0;
foreach( $array as $tmp){
if ($count <> 0){
$date = date("Y:m:d H:i:s");
$sql = "INSERT INTO $table set ";
$sql .= "detail = '{$tmp[2]}', shape = '{$tmp[3]}', qty = '{$tmp[4]}', price = '{$tmp[5]}', percent = '{$tmp[6]}', colour = '{$tmp[7]}', clarity = '{$tmp[8]}', prop = '{$tmp[9]}', polish = '{$tmp[10]}', smy = '{$tmp[11]}', diam = '{$tmp[12]}', t_dep = '{$tmp[13]}', `table` = '{$tmp[14]}', fl = '{$tmp[15]}', colour_shade = '{$tmp[16]}', cert = '{$tmp[17]}', cert_no = '{$tmp[18]}', per_kg = '{$tmp[19]}', selling_price = '{$tmp[20]}', status = 'new', create_date = '{$date}'";
//echo $sql."<br>";
//exit();
if (!($result = #mysql_query($sql) or die("Error:" . mysql_error().$sql)))
showerror();
$total++;
}
$count++;
}
return $total;
}
function empty_data($table){
if($table == "fancy_table"){
$s3 = "select * from $table where file != ''";
$r3 = mysql_query($s3);
while($d3 = mysql_fetch_array($r3)){
$del_lo_l="../../_files/fancy_product/".$d3['file'];
if(file_exists($del_lo_l))
{
#unlink($del_lo_l);
}
}
}
$s4 = "truncate table `$table`";
mysql_query($s4);
$s5 = "OPTIMIZE TABLE `$table`";
mysql_query($s5);
}
//error_reporting(E_ALL ^​​ E_NOTICE);
$action = $_REQUEST['action'];
if($_POST){
if($action == "empty"){
empty_data("artwork");
}else if($action == "imported"){
$Import_TmpFile = $_FILES['file']['tmp_name'];
$data = new Spreadsheet_Excel_Reader();
$data->setOutputEncoding('UTF-8');
$data->read($Import_TmpFile);
$total = 0;
//for ($i = 4; $i <= $data->sheets[0]['numRows']; $i++) {
for ($i = 4; $i <= 65536; $i++) {
if ($data->sheets[0]['cells'][$i][2] <> ""){
$sql = "INSERT INTO artwork set detail = '".$data->sheets[0]['cells'][$i][2]."', shape = '".$data->sheets[0]['cells'][$i][3]."', qty = '".$data->sheets[0]['cells'][$i][4]."', price = '".$data->sheets[0]['cells'][$i][5]."', percent = '".$data->sheets[0]['cells'][$i][6]."', colour = '".$data->sheets[0]['cells'][$i][7]."', clarity = '".$data->sheets[0]['cells'][$i][8]."', prop = '".$data->sheets[0]['cells'][$i][9]."', polish = '".$data->sheets[0]['cells'][$i][10]."', smy = '".$data->sheets[0]['cells'][$i][11]."', diam = '".$data->sheets[0]['cells'][$i][12]."', t_dep = '".$data->sheets[0]['cells'][$i][13]."', `table` = '".$data->sheets[0]['cells'][$i][14]."', fl = '".$data->sheets[0]['cells'][$i][15]."', colour_shade = '".$data->sheets[0]['cells'][$i][16]."', cert = '".$data->sheets[0]['cells'][$i][17]."', cert_no = '".$data->sheets[0]['cells'][$i][18]."', per_kg = '".$data->sheets[0]['cells'][$i][19]."', selling_price = '".$data->sheets[0]['cells'][$i][20]."', status = 'new', create_date = now()";
$result = #mysql_query($sql);
$total++;
}
}
echo $total;
//$total = sava_data($array, "artwork");
}else if($action == "fancy_imported"){
$Import_TmpFile = $_FILES['file']['tmp_name'];
$data = new Spreadsheet_Excel_Reader();
$data->setOutputEncoding('UTF-8');
$data->read($Import_TmpFile);
$total = 0;
//for ($i = 4; $i <= $data->sheets[0]['numRows']; $i++) {
for ($i = 4; $i <= 65536; $i++) {
if ($data->sheets[0]['cells'][$i][2] <> ""){
$sql = "INSERT INTO fancy_style set detail = '".$data->sheets[0]['cells'][$i][2]."', artworktype = '".$data->sheets[0]['cells'][$i][3]."', shape = '".$data->sheets[0]['cells'][$i][4]."', qty = '".$data->sheets[0]['cells'][$i][5]."', colour = '".$data->sheets[0]['cells'][$i][6]."', cut = '".$data->sheets[0]['cells'][$i][7]."', measurements = '".$data->sheets[0]['cells'][$i][8]."', treatment = '".$data->sheets[0]['cells'][$i][9]."', origin = '".$data->sheets[0]['cells'][$i][10]."', comments = '".$data->sheets[0]['cells'][$i][11]."', cert = '".$data->sheets[0]['cells'][$i][12]."', cert_no = '".$data->sheets[0]['cells'][$i][13]."', `per_kg` = '".$data->sheets[0]['cells'][$i][14]."', status = 'new', create_date = now()";
$result = #mysql_query($sql);
$total++;
}
}
echo $total;
}else if($action == "fancy_empty"){
empty_data("fancy_style");
}
}
//exit();
jsRedirect(geturlname().".php?action=".$action."&rows=".$total);
?>
<? include("../include/end.inc.php");?>

How to get the error rows values in php import

Hai i am using php to import a .csv file. The code is working fine. Now i am showing only error message if the data is not import means. I want to show the error message with wrong fileds. Here is my code :
if (isset($_POST["submitbutton"])) {
if (!empty($_FILES['file']['name'])) {
if (pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION) == 'csv') {
$handle = fopen($_FILES['file']['tmp_name'], "r");
//Grab the header in csv
$headers = fgetcsv($handle, 1000, ",");
$not_valid = [];
$i = 1;
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$aValid = false;
$field1 = mysqli_real_escape_string($dbConnection, $data[0]);
$field2 = mysqli_real_escape_string($dbConnection, $data[1]);
$field3 = mysqli_real_escape_string($dbConnection, $data[2]);
$field4 = mysqli_real_escape_string($dbConnection, $data[3]);
/* To Upload course Subscription data only course_id equal (25-11-2015) */
$sql = "select * from m_tl_course where id='$field2'";
$check = mysql_query($sql);
$sql1 ="select * from m_tl_user where id ='$field1'";
$check1 = mysql_query($sql1);
$sql4 = "select * from m_tl_role where id = '$field4'";
$check4 = mysql_query($sql4);
$sql2 = "select * from m_tl_subscription inner join m_tl_mastercourse on m_tl_subscription.Master_id = m_tl_mastercourse.Id where m_tl_mastercourse.LMS_Course_Id = '$field2'";
$check2 = mysql_query($sql2);
//$sql3="SELECT * FROM m_tl_role_assignments inner join m_tl_context where m_tl_role_assignments.userid='$field1' and m_tl_role_assignments.roleid='$field4' and m_tl_context.instanceid='$field2' and m_tl_context.contextlevel='50' ";
$time=strtotime("now");
$enrol="manual";
if((mysql_num_rows($check) > 0 && mysql_num_rows($check1) > 0 && mysql_num_rows($check4) > 0 ) && ( mysql_num_rows($check2) < 1 && mysql_num_rows($check3) < 1)) {
$aValid = true;
} else {
$not_valid[] = $i;
}
if ($aValid) {
$ret = "select m_tl_mastercourse.* from m_tl_mastercourse inner join m_tl_course on m_tl_mastercourse.LMS_Course_ID = m_tl_course.id where m_tl_course.id='$field2'";
$result=get_records_sql($ret,$limitfrom='', $limitnum='');
foreach($result as $res) {
$master_id = $res->Id;
}
$ret1 = "select * from m_tl_user where id='$field1'";
$result1=get_records_sql($ret1,$limitfrom='', $limitnum='');
foreach($result1 as $res1) {
$user_id = $res1->id;
}
$ret2="SELECT m_tl_context.id FROM m_tl_context inner join m_tl_course on
m_tl_context.instanceid=m_tl_course.id where m_tl_course.id = '$field2' and m_tl_context.contextlevel = '50' ";
$result3=get_records_sql($ret2,$limitfrom='', $limitnum='');
foreach($result3 as $res2) {
$context_id = $res2->id;
}
$import1= "Insert into m_tl_role_assignments values('','$field4','$context_id','$user_id','0','$time','0','0','$roleid','$enrol','0')";
mysql_query($import1);
$import = "INSERT into m_tl_subscription values('','$user_id','$master_id')";
mysql_query($import);
}
$i++;
}
fclose($handle);
if (!empty($not_valid)) {
$total_rows = $i - 1;
$valid_rows = $i - 1 - count($not_valid);
$invalid_rows = count($not_valid);
$v_ids = implode(', ', $not_valid);
echo "You are Uploading " . $total_rows. " Records. " . " <br><br> ". "In this " . $valid_rows . " Records are Inserted Successfully. and " . $invalid_rows . " records are failed to insert. " ."<br><br>". " So Please check the following csv Row Number's - " . $v_ids;
} else {
echo "Course Subscription Uploaded Successfully";
}
} else {
echo "<script>alert('csv files only allowed to upload')</script>";
}
} else {
echo "<script>alert('Please select a file')</script>";
}
}
if (is_uploaded_file($_FILES['file']['tmp_name']) && $_FILES['file']['error'] == 0) {
$target_Path = "../moodle/upload/";
$target_Path = $target_Path . basename($_FILES['file']['name']);
$file_location = move_uploaded_file($_FILES['file']['tmp_name'], $target_Path);
}
How to get the particular error field value.

alert duplicate records in csv upload

my csv upload code is like this want to alert duplicate records which are already exists in database i am getting result with $status variable what should i do to alert every duplicate records what is way to alert every duplicate records
if(isset($_POST["Import"]))
{
$filename=$_FILES["file"]["tmp_name"];
if($_FILES["file"]["size"] > 0)
{
$row = 1;
if (($handle = fopen("$filename", "r")) !== FALSE)
{
while (($data = fgetcsv($handle)) !== FALSE)
{
$num = count($data);
$row++;
for ($c=0; $c < $num; $c++) {
if($c!="" && $c+1!="" && $c+2!=""){
$a[] = $data[$c];
}
}
}
$total = count($a);
$m=0;
$k = 1;
for ($c=0; $c < $total; $c++)
{
$address[$m][] = $a[$c] ;
$z = $address[$m][0];
$q = $address[$m][1];
$q .= $address[$m][2];
$q .= $address[$m][3];
$q .= $address[$m][4];
$q .= $address[$m][5];
$q .= $address[$m][6];
$q .= $address[$m][7];
$q .= $address[$m][8];
$q .= $address[$m][9];
if($a[$c]=="")
{
if($k!=1)
{
$selectcon = "SELECT user_id FROM contact
WHERE user_id = '".$z."'";
$selectRes = mysql_query($selectcon);
if($rows = mysql_fetch_array($selectRes))
{
$user_id = $rows['user_id'];
if($user_id == $z)
{
$staus = 1;
}
else
{
$staus = 1;
}
}
$insertParty = "INSERT INTO contact(user_id)values('$z')";
$res = mysql_query($insertParty);
$contact_id = mysql_insert_id();
$insertAddress = "INSERT INTO address(contact_id,address)VALUES($contact_id,'$q')";
$insertAddressRes = mysql_query($insertAddress);
if(!$insertAddressRes)
{
echo "<sctipt>";
echo "sweetAlert('oops','Import Data Fail','error')";
echo "</sctipt>";
}
else
{
echo "<script>";
echo "swal('Sucess!', 'File Imported Sucessfully!','success')";
echo "</script>";
}
$m++;
}
$k++;
}
}
fclose($handle);
}
}
}
?>
You need to make a unique row inside database. You can't do it with PHP.
Add all columns to a single UNIQUE index, the you can't insert duplicate rows in that table.

Categories