CSV-> DB link interface

Status
Niet open voor verdere reacties.

timmeijers

Gebruiker
Lid geworden
6 apr 2007
Berichten
12
Hallo ik moet een site maken die CSV(excel) bestanden upload, en mensen de optie krijgen om tabellen van het excel bestand te linken met die in de DB, ik heb momenteel upload functie... en hoe je het in de database krijgt... maar nu moet ik nog er tussen een interface bouwen die de tabellen linkt...

iemand een idee hoe je dat doet?

voorbeeld van wat ik wil (DB = MySQL)

1zmiijd.png

2f07rk2.png

1zokftj.png

1zockrk.png
 
Uhm Volgens mis ik ergens een logica. Je upload je CSV in een bestaande tabel of een nieuwe tabel? Het lijkt alsof je het in een bestaande tabel wil uploaden, maar dan hoef je niet te linken. Als het twee aparte tabellen worden kun je ze via een join query linken, maar dat veranderd niets in de database. Ik snap alleen het nut hiervan dan niet, waarom allemaal tabellen uploaden als je de oude data behoud?
 
Uhm Volgens mis ik ergens een logica. Je upload je CSV in een bestaande tabel of een nieuwe tabel? Het lijkt alsof je het in een bestaande tabel wil uploaden, maar dan hoef je niet te linken. Als het twee aparte tabellen worden kun je ze via een join query linken, maar dat veranderd niets in de database. Ik snap alleen het nut hiervan dan niet, waarom allemaal tabellen uploaden als je de oude data behoud?

kijk je hebt een database. daarin zit een tabel met product informatie. die word constant ge-update, maar mensen maken geen sql files thuis. dus doen we vanaf Excel naar database. maar als je dat doet.. zijn de namen van de tabellen niet altijd gelijk aan de tabellen in de database dus moet je hun de mogelijkheid geven om te zeggen van, die tabel hoort bij die tabel. en die hoort bij die. en je zet de data die achter die tabellen zit in de database.

zie je nu de logica?
 
Je laat mensen zelf de link logica doen? Als in: je vertrouwd gebruikers om niet je volledige database te wissen en nooit verkeerd te clicken? Nee die logica zie ik dus niet :P . Je kunt via aliases denk ik wel bereiken wat je wil, maar ik zou je toch aanraden om de excel kant van het verhaal te standaardiseren. Als mensen integer values gaan koppelen aan text en vise versa ga je onherroepelijk problemen krijgen in de rest van je chain en zelfs mogelijk database corruptie.
 
Ik hoop dat php geen probleem is dient aangepast te worden naar uw behoeften
let op OO class
PHP:
<?PHP
 /**
 * @author Lieven Roegiers
 * @copyright 2007 refactor 2009
 * @CMS autosite
 * opensource http://code.google.com/p/autosite/
 */
if (!function_exists('csv_plus')){//include_once its when it is include in the php lib
class csv_plus{
	private	$Delimiter=',';
	private $maxfilesize=1000;
	private $filelocation;
    private $minlivetime =0;
	private $file;
	private $errornr;
	/** 
	 * @param mixed $pathname
	 * @param mixed $filelocation
	 * @param integer $lifetime
	 * @return
	 */
	public function __construct($pathname,$filelocation,$lifetime = 0){
		$this->filelocation=$pathname.$filelocation;
		$this->minlivetime = $lifetime;//(1 * 1 * 60 * 60);
	}
	/**
	 * @param string $mode
	 * @return
	 */
	private function open($mode='a+'){
		return($this->is_readytouse()&& $this->file = fopen($this->filelocation,$mode)); //File!found E53 
	}
	/**
	 * @param mixed $arrData
	 * @param bool $del_oldlines
	 * @return
	 */
	function save_line($arrData,$del_oldlines=true){
		if ($del_oldlines){
			$this->del_oldlines();
		}
		$timestamp = ($this->minlivetime>0)?(time()+$this->minlivetime).$this->Delimiter:"";
		$datastring =" ".$timestamp.implode($this->Delimiter,$arrData);//space on the front is for search
		$datastring = $this->Aln2br($datastring)."\n";
		return ($this->open()&& fputs($this->file, $datastring));
	}
	/**
	 * @return bool
	 */
    private function Aln2br($txt){
        return strtr($txt, array("\r\n" => '<br/>', "\r" => '<br/>', "\n" => '<br/>'));
    }
    private function Abr2ln($txt){
        return strtr($txt, array("<br />" => "\n", "<br/>" => "\n"));
    }
	public function is_readytouse(){
		return(isset($this->filelocation)&& is_file($this->filelocation));
	}
	/**
	 * @param mixed $source fname
	 * @param string $destprefix
	 * @return bool
	 */
	private function bakup($source,$destprefix=".BAK"){
		return (is_file($source) && (filesize($source)>0)&& !copy($source, $source.$destprefix));
	}
    /**
	 * @return void
	 */
 	private function add($source,$destprefix=".BAK"){
		return (is_file($source) && (filesize($source)>0)&& !copy($source, $source.$destprefix));
	}
    /**
	 * @return void
	 */
	private function del_oldlines(){
		if ($this->is_readytouse()&& filesize($this->filelocation)>$this->maxfilesize){
			if ($this->bakup($this->filelocation)){//rename($path.$file, $path.$bakfile);
				unlink ($this->filelocation);
			}
			$lines = file($this->filelocation.".BAK");
			if (!$this->open()) {
				foreach ($lines as $line_num => $line){
					$kkey=explode(',', $line);
					if((time() > $kkey[0])){//releastijd
					}elseif(fputs($file,$line)){//infileplaatsen
					}else {//echo "error write bakup";
					}
				}		
			}
		}	
	}
	/**
	 * @param mixed $Fname
	 * @return
	 */
	function HTML_listvieuw($Fname){
		$row = 1;
		$fp = fopen ($fname,"r");
		while ($data = fgetcsv($Fname,1000,",")) {
		    $num = count ($data);
		    print "<p> $num velden in regel $row: <br>\n";
		    $row++;
		    for ($c=0; $c < $num; $c++) {
		        print $data[$c] . "<br>\n";
		    }
		}	
	}
	/*function HTML_table($Fname){
		$row = 1;
		$fp = fopen ($fname,"r");
		while ($data = fgetcsv($Fname,1000,",")) {
		    $num = count ($data);
		    print "<p> $num velden in regel $row: <br>\n";
		    $row++;
		    for ($c=0; $c < $num; $c++) {
		        print $data[$c] . "<br>\n";
		    }
		}	
	}*/
	/**
	 * @param mixed $findstring
	 * @param integer $resul
	 * @return string line
	 */
	function find_line($findstring,$resul=1){
		if ($this->open()){
			while (!feof($this->file))
	    		{$line = fgetcsv($this->file,1024,",");
	    			if(is_array ($line)){
						if (!$pos = array_search($findstring,$line )){ 
	     				//print_r($line); //niet gekozen items	
	     				}else{
	     					return  $line ;
	     					exit;	
						}
	     			}else{
						//fun_error(381);//Invalid array
					}
	 		$line=""; 
			}
		}
	}
    	/**
	 * @param mixed $findstring
	 * @param integer $resul
	 * @return string line
	 */
	private function pos_line($findstring,$resul=1){
		if ($this->open()){
			while (!feof($this->file))
	    		{$line = fgetcsv($this->file,1024,",");
	    			if(is_array ($line)){
						if (!$pos = array_search($findstring,$line )){ 
	     				//print_r($line); //niet gekozen items	
	     				}else{
	     					return  $line ;
	     					exit;	
						}
	     			}else{
						//fun_error(381);//Invalid array
					}
	 		$line=""; 
			}
		}
	}
	/**
	 * @return
	 */
	function __destruct(){
		//fclose ($this->file);
	}	 	
}
}
?>
dus nadien ga je validatie uitvoeren nooit vergeten en ook de file corupt kunnen aanduiden en bijgevolg dan niet gebruiken.

PHP:
<?php
 /**
 * @author Lieven Roegiers
 * @copyright 2009 
 * @CMS autosite
 * opensource http://code.google.com/p/autosite/
 * <script language='JavaScript' src='<?php print $autosite['javascript']?>form.val.js'></script>
 * <form onsubmit="return formCheck()" enctype="text/plain" method="GET"></form>
*/
class valid{
   private	$msgarr;
   private	$errors=array();//aso_array
   private	$tovalidate;
   private	$isvalid= true;
   function __construct(){
   		//$this->seterrormsg("notexist","ERROR NOTEXIST Formfield:","is not exist watch to your form");	
   }
   /**
    * @return bool
    */
   public function is_valid(){
		return $this->isvalid;
   }
   /**
    * @param mixed $GETorPOST
    * @param mixed $formdata
    * @param bool $is_inject
    * @return assoarr
    */
   public function dovalidation(&$GETorPOST,&$formdata,$is_inject=true){
   		$returnval = array();//array for to save !!!!only valid values!!!!
   		$this->errormsg="";
   		$this->isvalid=true;
		$formfields = $formdata['items'];
		$tovalidate = $formdata['tovalid'];
		$validfine=is_array($tovalidate);
		//print  "<br /> validatefine:".$validfine."<br />";
		if(is_array($formfields)){
			foreach($formfields as $key=>$value){
				$value = $this->makeitvalidate($key);
				if(is_array($GETorPOST[$key])){
					$GETorPOST[$key] = "".implode(",",$GETorPOST[$key])."";
				}
				$value = illegalcharconverter($GETorPOST[$key]);
				if($validfine&& array_key_exists($key,$tovalidate)&&!array_key_exists($key,$GETorPOST)){
					//<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< formfield is not exist but not to valid >>>>>>>>>>>>>>>>>>>>>>
					//!!!!!!!!!!!!!!OK!!!!!!!!!!
                    $this->setok("[must not valid ok]",$key);
					$returnval[$key]=$value;//add val to array
                    
				}elseif(!array_key_exists($key,$GETorPOST)){
					//<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< formfield is not exist >>>>>>>>>>>>>>>>>>>>>>
					$this->seterror("notexist",$key);
					return; //form NOT ok
				}else{
					$tmp =(isset($value))? addslashes($value) : "" ;
					if ($validfine && trim($tmp) == ""){
//<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<not validation fine but empty >>>>>>>>>>>>>>>>>>>>>>
						$this->seterror("empty",$key);
					}elseif($validfine && !array_key_exists($key,$tovalidate)){
//<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<validation fine but field must not tovalidate >>>>>>>
						//!!!!!!!!!!!!!!OK!!!!!!!!!!
						if($testinjection &&  is_sqlinject($value)){
							$this->seterror("injection",$key);
							return;
						}
                        $this->setok("[ok]",$key);
						$returnval[$key]=$value;//add val to array
					}elseif($validfine && $this->validatefine($key,$tmp)){
//<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<validation fine and field is also validfine >>>>>>>
						//!!!!!!!!!!!!!!OK!!!!!!!!!!
						if($testinjection && is_sqlinject($value)){
							$this->seterror("injection",$key);
							return;
						}
                        $this->setok("[ok]",$key);
						$returnval[$key]=$value;//add val to array
					}else{
						$this->seterror("??!ERROR!??",$key);
					}	
				}
			}
		}else{
			$this->seterror("!implementation!",$key);
		}
		//$this->test($formfield,$returnval);	
   		return $returnval;
   }
   /**
    * @param mixed $key
    * @param mixed $value
    * @param mixed $testinjection
    * @return
    */
   private function validatefine($key , $value,$testinjection){	
	   	switch($key):
		 	case "email":
			case "mail":
				return is_email($value); 
				break;
			case "tel":
			case "telefoon":
				return true;// is_numeric($value); 
				break;
			case "name":
			case "naam":
				return is_name($value);
				break;
			default: 
				return true;
				break;
		endswitch;
   }
   /**
    * @param mixed $key
    * @return
    */
   private function makeitvalidate($key){	
	   	switch($key):
			case "now.date":
				return date("l j F Y"); 
				break;
		endswitch;
   } 
   /**
    * @param mixed $post
    * @param mixed $keys
    * @return
    */
   private function get_arrfirstitem($post,$keys){//indien te valideren geeft hij de value
		foreach ($keys as $key) {
			if(array_key_exists($key,$this->formitemlist)){
				return $this->formitemlist[$key];
			}
		}
		return null;
   }
   
   /**
    * @param mixed $tovalidate
    * @return
    */
   public function setvalidatefine($tovalidate){
   	  $this->$tovalidate=$tovalidate;
   }
   /**
    * @return
    */
   private function getvalerrors(){
	 return $this->errormsg;
   }
   /**
    * make a "notfound","fatal","notexist","injection"
    * @param mixed $name
    * @param mixed $msg
    * @return
    */
   public function seterrormsg($name,$msg){
   		$this->msgarr[$name]=$msg;   	
   }
   /**
    * @param mixed $msg
    * @param mixed $key
    * @return
    */
   private function seterror($msg,$key){
   		$this->isvalid=false;
		$this->errors["key".$key]= $msg;
   }
   /**
    * @param mixed $msg
    * @param mixed $key
    * @return
    */
   private function setmsg($msg,$key){
		$this->errors["key".$key]= $msg;
   }
   /**
    * @return
    */
   public function geterrors(){
   	 return $this->errors;
   }
   /**
    * @return
    */
   private function setok(){}
   /**
    * @return
    */
   public function __printerrors(){
   		print "<div class='ERROR'>";
   		array_walk($this->errors,"__ERRtostring");
   		print "</div>";
   		print "<br /><input type='button' id='button' onClick='javascript:history.go(-1)' value=' Return '>\n";
   }
   /**
    * @param mixed $item
    * @param mixed $key
    * @param string $ad
    * @return
    */
   private function __ERRtostring($item, $key,$ad ="<br />"){
   		print $key."".$item.$ad;
   }
   /**
    * @param mixed $formfield
    * @param mixed $returnval
    * @return
    */
   private function test($formfield,$returnval){
   		print("<div class='ERROR apanel'>test dovalidation formfields");
		print_r($formfields);
		print_r($returnval);
		print("</div>");
   }
}
/**
 * @param string;
 * @return boolean;
 * @param mixed $str
 * @return
 */
function is_email($str){
	return (isset($str)&&eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$", $str));
}
/**
 * @param mixed $bankrekeningnummer
 * @return
 */
function is_reknl($bankrekeningnummer){
    $som = NULL;
    if(strlen($bankrekeningnummer)==9){
        for ($i=0; $i<=8; $i++){
            $som += ($bankrekeningnummer[$i] * (9 - $i));
        } 
       	return ($som % 11 == 0);//valid invalid
    }
    return false;
}
/**
 * @param mixed $bankrekeningnummer
 * @return bool
 */
function is_rek($bankrekeningnummer){
	return "underconstruction";
}
/**
 * @param mixed $reknr
 * @return bool
 */
function is_postbank($reknr){
	$len = strlen($reknr);
	return ($len > 7 && $len < 3);
}
/**
 * @param mixed $var
 * @return bool
 */
function is_positive_whole_number($var){
	return (is_whole_number($var) && $var>0);
}
/**
 * @param mixed $var
 * @return bool
 */
function is_whole_number($var){
	return (is_numeric($var)&&(intval($var)==floatval($var)));
}
/**
 * @param string;
 * @return boolean;
 * <NL>is er een klinker.
 */
function is_avowel($var,$max){
	$max =($max<1)?5:$max;
	for ($i = 0; $i < $max; $i++) {
	 	switch($arr[$i]):
		case "a":
		case "e":
		case "i":
		case "o":
		case "u":
				return true;
				break;
	    endswitch;	
	}
	return false;
}
/**
 * @param mixed $var
 * @return
 */
function is_name($var){
	return (is_avowel($var,5));//not posible name =>5 =>"schr"
}
/**
 * @param mixed $var
 * @return
 */
function is_sqlinject($var){//DROP TABLE	
 	return pos($var,"DROP TABLE")||pos($var,"DROP")||(pos($var," WHERE ") && pos($var," OR "))||pos($var,"SELECT * FROM");
}
/**
 * @param mixed $var
 * @return
 */
function is_phpinject($var){	
 	return pos($var,"print_r")||pos($var,"DROP");
}
/**
 * @param mixed $var
 * @return
 */
function is_spaminject($var){	
 	return pos($var,"sex")||pos($var,"SEX");
}

// %&#37   (&#40   )&#41
function illegalcharconverter($str){
    $chars=array("&"    ,"<"   , ">"   ,"!"    ,'"'    ,","    ,"$"    ,"'"    ,"*"    ,"+"   );
    $ascii=array("&","&lt;", "&gt;","!",""",",","$","'","*","+");
    return str_replace($chars,$ascii , $str); 
}

















/*
Wat zou er gebeuren als je het document als volgt aanroept?
files.php?login_id=1234567890 OR 1=1
De volgende SQL query wordt uitgevoerd:
SELECT * FROM files WHERE id = 1234567890 OR 1=1

*/
?>
dus nu zou je al een deeltje moeten zien zitten de rest van mysql kan bijna iedereen dus vermoed ik dat de anderen zouden verderhelpen bij volgende faze.

LET OP het is een zeer goede opgave en je doet ze best zo goed mogelijk nadien kan je er een webshop mee bouwen en als je ooit webdeveloper wordt zal je merken dat vroeger veel csv gebruikt werd dus zal je deze ook veel als uitvoerformaat vinden
 
Status
Niet open voor verdere reacties.
Terug
Bovenaan Onderaan