How to get the error rows values in php import - php

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.

Related

Import csv from file with dynamic table head

I'm having a problem with my importing csv script into mysql:
from now i can put the data from csv into mysql but only with strictly header arrange, but my export from csv always change the head of table, and i cannot control it.
my csv file is different from the table for example:
Name Status Last_name email_address employee_address phone_number
And all i need is to take the column name and put it into right column from table.
Thanks.
if (isset($_POST["import"])) {
$fileName = $_FILES["file"]["tmp_name"];
if ($_FILES["file"]["size"] > 0) {
$file = fopen($fileName, "r");
$captabel = true;
$flag = true;
while (($column = fgetcsv($file, 1000, ",")) !== FALSE) {
if($captabel) { $captabel = false; continue; }
$celuleNecesare = array(0);
foreach ($celuleNecesare as $value) {
if(trim($column[$value]) == "" || $column[$value] == NULL)
$flag = false;
}
if($flag) {
$query = "INSERT into test (name ,employee_status, surname, email, address, phone)
values ('" . $column[2] . "','" . $column[7] . "','" . $column[8] . "','" . $column[5] . "','" . $column[0] . "','0" . $column[3] . "')";
$result = mysqli_query($conn, $query);
if (! empty($result)) {
$type = "success";
header( 'refresh: 0; success.php' );
} else {
$type = "error";
$message = "Problem in Importing CSV Data";
}
}
}
}
}
Just taking a quick look at your code, I have noticed something that is amiss:
if (isset($_POST["import"]))
{
$fileName = $_FILES["file"]["tmp_name"];
if ($_FILES["file"]["size"] > 0)
{
$file = fopen($fileName, "r");
$captabel = true;
$flag = true;
while (($column = fgetcsv($file, 1000, ",")) !== FALSE)
{
if($captabel)
{
$captabel = false;
continue;
}
$celuleNecesare = array(0); <-- Is this being set externally to the code listed here.
foreach ($celuleNecesare as $value)
{
if(trim($column[$value]) == "" || $column[$value] == NULL)
$flag = false;
}
if($flag)
{
$query = "INSERT INTO test
(name ,employee_status, surname, email, address, phone)
VALUES
('" . $column[2] . "','" . $column[7] . "','" . $column[8] . "','" . $column[5] . "','" . $column[0] . "','0" . $column[3] . "')";
$result = mysqli_query($conn, $query);
if (! empty($result))
{
$type = "success";
header( 'refresh: 0; success.php' );
}
else
{
$type = "error";
$message = "Problem in Importing CSV Data";
}
}
}
}
}
You have the line $celuleNecesare = array(0); and then loop through it, but that does nothing in itself.
Your code should be something similar to this:
if (isset($_POST["import"]))
{
$fileName = $_FILES["file"]["tmp_name"];
if ($_FILES["file"]["size"] > 0)
{
$file = fopen($fileName, "r");
$captabel = true;
$flag = true;
// Get the first row as the header row.
$headers = fgetcsv($file, 1000, ",");
// Variables to be used.
$counter = 0;
$nameCol = 0;
$statuscol = 0;
$lastnameCol = 0;
$emailAddressCol = 0;
$employeeAddressCol = 0;
$phoneNumberCol = 0;
foreach($headers as $header)
{
// Name Status Last_name email_address employee_address phone_number
// Lets work through the header row.
switch($header)
{
case 'Name' : $nameCol = $counter;
break;
case 'Status' : $statusCol = $counter;
break;
case 'Last_name': $lastNameCol = $counter;
break;
case 'email_address' : $emailAddressCol = $counter;
break;
case 'employee_address' : $employeeAddressCol = $counter;
break;
case 'phone_number' : $phoneNumberCol = $counter;
break;
default : die("Unknown column, ".$header);
break;
}
$counter++;
}
while (($column = fgetcsv($file, 1000, ",")) !== FALSE)
{
$query = "INSERT INTO test
(name ,employee_status, surname, email, address, phone)
VALUES
('" . $column[$nameCol]."','".$column[$employeeStatusCol]."','".$column[$lastnameCol]."','".$column[$emailAddressCol]."','".$column[$employeeAddressCol]."','0".$column[$phoneNumberCol]."')";
$result = mysqli_query($conn, $query);
// This section below would stop after the first record!!!!!
if (! empty($result))
{
$type = "success";
header( 'refresh: 0; success.php' );
}
else
{
$type = "error";
$message = "Problem in Importing CSV Data";
}
}
}
}
Your IF condition at the end would mean that you are only inserting a single record. Not sure if that is meant, but since you have a while loop for reading in the data, thought there would be many more records.

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.

<<From csv to array to database issue: not loading entire fail or failing

I need some help over here... what I try to do is to read a csv file (which is already converted from xls) then get all lines and put every field of a line into db
name,lastname,idprod
name,lastname,idprod
name,lastname,idprod
the issue might be that some fields are empty,
but after launching the script it starts working for like 1883 lines and put them in database, then the
$row["productid"] ." - ". $productid ."";
starts outputting empty value
here -
for the rest of the lines
Sorry for code in pastebin, this editor won't allow me to post this question with code saying some issues...
<?php
$rowe = 0;
$exploded;
$data;
$ass = 0;
$hardcore[0][0];
$swag = 0;
if (($handle = fopen("price_list_EN.csv", "r")) !== FALSE) {
$ass = 0;
$swag++;
while (($linebyline = fgetcsv($handle, 1000, ",")) !== FALSE) {
//$linebyline = explode(",", $linebyline);
$hardcore[$rowe][$ass] = $linebyline[$ass];
//echo $linebyline[$ass];
$exploded[$rowe][$ass] = $hardcore[$rowe][$ass];
//echo $exploded[$rowe][$ass];
//while (($explode = fgetcsv($linebyline, 1000, ",")) !== FALSE)
{
$num = count($data);
if ($ass == count($linebyline)){
echo "<br>";
$ass = 0;
$rowe++;
}else{
$ass++;
}
}
//}
fclose($handle);
}
//$linebyline = explode("\n", $_POST['message']);
//$linebyline = explode("\n", $data2);
//echo count($data2);
$imo=0;
$normovalue=0;
$normovalue2=0;
$normovalue3=0;
for ($i=0;$i<30000;$i++){
if ($exploded[$i][0] == ''){
$imo = $i;
}
}
for ($rowe=0;$rowe<$imo;$rowe++){
for ($ass=0;$ass<9;$ass++){
//$exploded = explode(";", $linebyline[$i]);
$link = mysql_connect('localhost', 'root', '');
if (!$link) {
die('Not connected : ' . mysql_error());
}
// make foo the current db
$db_selected = mysql_select_db('moday', $link);
if (!$db_selected) {
die ('Can\'t use foo : ' . mysql_error());
}
}
if ($exploded[$rowe][0] !== "" || $exploded[$rowe][4] !== "" ||
$exploded[$rowe][3] !== "" || $exploded[$rowe][1] !== ""){
$productid = $exploded[$rowe][0];
$price = round($exploded[$rowe][4],2);
$disponibilita = $exploded[$rowe][3];
$indir = "null";
$descrizione = $exploded[$rowe][1];
$conn = new mysqli("localhost", "root", "", "moday");
$sql = "SELECT productid from data where productid='$productid'";
$result = $conn->query($sql);
if ($result->num_rows == 0) {
mysql_query("INSERT INTO
data(productid,price,disponibilita,indir,descrizione)
values('$productid','$price','$disponibilita','$indir','$descrizione')")
or die("Query non valida: " . mysql_error());
$normovalue++;
}else{
// output data of each row
while($row = $result->fetch_assoc()) {
if ($row["productid"] == $productid){
echo "here ". $row["productid"] ." - ". $productid ."";
if ("$exploded[$rowe][0] == '' || $exploded[$rowe][1] ==
'' || $exploded[$rowe][3] == '' || $exploded[$rowe][4] == '' ||
$exploded[$rowe][2] == ''|| $exploded[$rowe][5] hh "){
echo $exploded[$rowe][0];
echo $rowe;
}
echo "<br /> \n";
$sql2 = "UPDATE data SET price='$price',
disponibilita='$disponibilita' where productid='$productid'";
$normovalue2++;
$result2 = $conn->query($sql2);
}else{
}
}
}
/*$risultato = mysql_query("INSERT INTO
data(productid,price,disponibilita,indir,descrizione)
values('$productid','$price','$disponibilita','$indir','$descrizione')")
or die("Query non valida: " . mysql_error());
*/
//echo "<br /> \n"
}
}
$normovalue3 = $normovalue + $normovalue2;
echo "N.1 is $normovalue 2 is $normovalue2 3 is $normovalue3";
?>
Put the $result into the database, as you desire:
<?php
$csv = "Chris,Garcia,1\nJohn,Doe,2\nJames,Smith,3";
foreach(explode("\n", $csv) as $key => $value) {
$result = explode(",", $value);
echo "Name: " . $result[0] . ", Lastname: " . $result[1] . ", ID: " . $result[2] . "\n";
}
exit();
?>

How to count the uploaded data's through .csv in 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);

How to Validate Employee Id in Importing File in .CSV format to SQL?

How to Validate Employee Id in Importing File in .CSV format to SQL?
*a code that check if the data is already exist.
-->sample: if the Employee Id already exist it promts "Employee ID already Exist"..
if the rows in csv, you can make a array of csv rows.
$list =array();
$id = array();
while( ($rows= getcsv($hande)) !== false)
{
array_push($list, $rows);
array_push($id, $rows['emplyee_id']);
}
then check mysql or database
$check_id = implode(",", $id);
$que = "select employ_id from table where employ_id in ($check_id)";
at this time you can find employ_ids from database.
if you make employee_id column unique, your code would be like this
$result=mysqli_query($db_con", "insert into table (employ_id) values ('$empoy_id')";
if($result == false) // if employ_id alreay exists in table $result is false
{
}
but as i know, the best way using index is checking key is exists before inserting data not after inserting query failed.
This is my code:
`<?php
if ($_FILES["file"]["error"] > 0)
{
echo "Error: " . $_FILES["file"]["error"] . "<br>";
}
else
{
echo "Upload: " . $_FILES["file"]["name"] . "<br>";
echo "Type: " . $_FILES["file"]["type"] . "<br>";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br>";
echo "Stored in: " . $_FILES["file"]["tmp_name"];
$a=$_FILES["file"]["tmp_name"];
echo $a;
$connect = mysql_connect('localhost','root','');
if (!$connect) {
die('Could not connect to MySQL: ' . mysql_error());
}
//your database name
$cid =mysql_select_db('cgi_warehouse',$connect);
// path where your CSV file is located
//define('CSV_PATH','C:/xampp/htdocs/');
//<!-- C:\\xampp\\htdocs -->
// Name of your CSV file
$csv_file = $a;
if (($getfile = fopen($csv_file, "r")) !== FALSE) {
$data = fgetcsv($getfile, 1000, ",");
while (($data = fgetcsv($getfile, 1000, ",")) !== FALSE) {
//$num = count($data);
//echo $num;
//for ($c=0; $c < $num; $c++) {
$result = $data;
$str = implode(",", $result);
$slice = explode(",", $str);
$col1 = $slice[0];
$col2 = $slice[1];
$col3 = $slice[2];
$col4 = $slice[3];
$col5 = $slice[4];
$col6 = $slice[5];
$col7 = $slice[6];
$col8 = $slice[7];
$col9 = $slice[8];
$col10 = $slice[9];
$col11 = $slice[10];
$col12 = $slice[11];
$col13 = $slice[12];
$col14 = $slice[13];
$col15 = $slice[14];
$col16 = $slice[15];
$query = "INSERT INTO tools(tools_id, item_description, category_id, sn, qty, price, supplier, frm, location, ref_no, sender, receiver, date_receive, date_added, status, remarks) VALUES('".$col1."','".$col2."','".$col3."','".$col4."','".$col5."','".$col6."','".$col7."','".$col8."','".$col9."','".$col10."','".$col11."','".$col12."','".$col13."','".$col14."','".$col15."','".$col16."')";
$s=mysql_query($query, $connect );
}
}
echo "<script>alert('Record successfully uploaded.');window.location.href='#';</script>";
mysql_close($connect);
}
?>`

Categories