Error importing xls to postgres

Asked

Viewed 96 times

1

I am trying to import an XLS file into the Postgressql database, however when I run Submit on the page itself, the error below occurs:

Undefined offset: 1 in C: wamp www projects... line 59

Below, follow the code:

<div class="container-fluid"> 
	<fieldset class="bottom">
		<legend>Importação em Excel</legend>	
			<form action="#" method='post' enctype="multipart/form-data">
		<fieldset>
			<div class="form-group">
				<input type='file' name='sel_file' size='20'>
			</div>
		</fieldset>
	<input type='submit' name='submit' value='Importar' class="btn btn-success">
</form>

<?php
	
if(isset($_POST["submit"])){	

	if(!@($conexao=pg_connect("host=localhost port=5432 dbname=teste user=postgres password=****"))) {
		print "Não foi possível estabelecer uma conexão com o banco de dados.";
	} else {
	   print "Conexão OK!"; 
	}

     $fname = $_FILES['sel_file']['name'];
     $chk_ext = explode(".",$fname);

     if(strtolower($chk_ext[1]) == "xls"){
    
         $filename = $_FILES['sel_file']['tmp_name'];
         $handle = fopen($filename, "r");
		 
         while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
			 
           $sql = "INSERT into items(nome,email) values('$data[0]','$data[1]')";
 		   $result = pg_query($conexao, $sql);
         }
   
         fclose($handle);
         echo "Arquivo Importado com sucesso";
     }else{
         echo "Arquivo inválido";
     } 
 
}

?>
	

The table structure is very simple :

inserir a descrição da imagem aqui

And the XLS File :

inserir a descrição da imagem aqui

Thanks in advance for your attention.

  • Variables Array must be concatenated in SQL.: Ex.: ('".$data[0]."','".$data[1]."')

  • even then the error occurs: Undefined offset: 1 in C: wamp www urm projects... line 59 Line 59 -> $sql = "INSERT into items(name,email) values('". $data[0]." ','". $date[1]."')";

  • And the data, it comes correctly?

2 answers

1

I was able to enter the code below:

 $file   = $_FILES ['sel_file' ]['tmp_name'] ; 
	  $row = 1;
		if (($handle = fopen($file, "r")) !== FALSE) {
			while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
				//$num = count($data);
				$row++;

				$veiculo = $data[0]; 
				$rd =$data[1];

				$sql = "INSERT into items(veiculo,rd) values('".$veiculo."','".$rd."')";
				$rs = pg_query($conexao, $sql);
			}
			
			if ($rs){ 
				echo   "Arquivo importado com sucesso !" ; 
				fclose($handle);
			}else{ 
				echo   "Erro ao carregar o arquivo" ; 
			} 
		}

Therefore, I would like to get only the lines starting from line 6 by ignoring the header as below:

inserir a descrição da imagem aqui

0


Solved !

if ($getLinha == ''){
    $getLinhaValor = 6;
}else {
    $getLinhaValor = $getLinha ;
}

//obten a linha do arquivo conforme a escolha do usuario
if ($linha_count > $getLinhaValor ){
   ..... code
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.