Happy Codings - Programming Code Examples
Html Css Web Design Sample Codes CPlusPlus Programming Sample Codes JavaScript Programming Sample Codes C Programming Sample Codes CSharp Programming Sample Codes Java Programming Sample Codes Php Programming Sample Codes Visual Basic Programming Sample Codes


Php Programming Code Examples

Php > Database Related Code Examples

Load a file into a database or something

Load a file into a database or something <?php class LoadToDB { /* Declare class variables */ var $dbname; var $dbfields; var $dbfile; var $field_num; var $a_keys; var $separator; var $head; /* The constructor */ function LoadToDB($name, $file, $head, $separator = ',') { if($head) $this->head = 1; /* if head is set */ $this->separator = $separator; /* define separator */ $this->dbname = $name; /* wich table do we wanna insert into */ $this->dbfile = file("$file"); /* load the file into an array */ } function SetFields($fields) { $this->dbfields = $fields; /* copy */ $this->field_num = count($this->dbfields); /* count */ $this->a_keys = array_keys($this->dbfields); /* find keys */ } function LoadIntoDB() { $rows = count($this->dbfile); /* make the sting that is identical to all querys */ $start_query = "INSERT INTO ".$this->dbname." ("; for($i = 0; $i < $this->field_num; $i++) { if($i != 0) $start_query .= ", "; $start_query .= $this->dbfields[$this->a_keys[$i]]; } $start_query .= ") VALUES ("; /* Loop through all entrys and insert them */ for($i = $this->head; $i < $rows;$i++) { $query = $start_query; $this->dbfile[$i] = addslashes($this->dbfile[$i]); $n_row = explode($this->separator, $this->dbfile[$i]); for($j = 0; $j < $this->field_num; $j++) { if($j != 0) $query .= ", "; $query .= "'".$n_row[$this->a_keys[$j]]."'"; } $query .= ")"; mysql_query($query); if(mysql_affected_rows() < 1) return 0; // on failure } return 1; // on success } } ?>