Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

« Newer Snippets
Older Snippets »
Showing 1-4 of 4 total  RSS 

export and import by php

There are at least three ways to backup your MySQL Database :

Execute a database backup query from PHP file.
Run mysqldump using system() function.
Use phpMyAdmin to do the backup.


Execute a database backup query from PHP file

Below is an example of using SELECT INTO OUTFILE query for creating table backup :

<?php
include 'config.php';
include 'opendb.php';

$tableName = 'mypet';
$backupFile = 'backup/mypet.sql';
$query = "SELECT * INTO OUTFILE '$backupFile' FROM $tableName";
$result = mysql_query($query);


include 'closedb.php';
?>
To restore the backup you just need to run LOAD DATA INFILE query like this :

<?php
include 'config.php';
include 'opendb.php';

$tableName = 'mypet';
$backupFile = 'mypet.sql';
$query = "LOAD DATA INFILE 'backupFile' INTO TABLE $tableName";
$result = mysql_query($query);


include 'closedb.php';
?>
It's a good idea to name the backup file as tablename.sql so you'll know from which table the backup file is


Run mysqldump using system() function

PHP : Exportar CSV a mySQL / Export CSV to mySQL

Cóodigo fuente / Source code :

function exportarCSV_a_mySQL($fileCSV)
{
	$registros=0;

	$ruta=$fileCSV['tmp_name'];

	if(!file_exists($ruta))
	{return false;}

	$tabla=quitar_extension($fileCSV['name']);
	
	$borra_tabla="DROP TABLE `".$tabla."`";
	mysql_query($borra_tabla);
	$f=fopen($ruta,"r");
	if($f)
	{
		echo "<b>Guardando CSV en la BDD :</b><br />";
		$contenido=fread($f,filesize($ruta));
		fclose($f);
		$contenido=ereg_replace("\r\n", "\n" , $contenido); // convertimos windows a unix
		$lineas=explode("\n",$contenido);
		$titulo=explode(";",$lineas[0]);
		$NUM_CAMPOS=count($titulo);
		$sql_generado_para_eliminar="";
		$crear_tabla_campos="";
		for($i=0;$i<$NUM_CAMPOS;$i++)
		{
		$titulo[$i]=ereg_replace("\"", "" , $titulo[$i]); // kitamos comillas
		$sql_generado_para_eliminar.=" AND `".$titulo[$i]."` =''";
		$crear_tabla_campos.="`".$titulo[$i]."` varchar(60) NOT NULL";
			if($i+1!=$NUM_CAMPOS)// si no es el ultimo , ponemos coma
			{
			$crear_tabla_campos.=",";
			}
		}
		$crear_tabla="CREATE TABLE `".$tabla."` (".$crear_tabla_campos.") ENGINE=MyISAM DEFAULT CHARSET=latin1;";
		mysql_query($crear_tabla);
		$linea=1;
		do
		{
			$insertar_titulos="";
			$insertar_campos="";
			$campo=explode(";",$lineas[$linea]);
			for($i=0;$i<$NUM_CAMPOS;$i++)
			{
			$campo[$i]=ereg_replace("\"", "" , $campo[$i]);
			$insertar_titulos.=" `".$titulo[$i]."` ";
			$insertar_campos.=" '".$campo[$i]."' ";
				if($i+1!=$NUM_CAMPOS)// si no es el ultimo , ponemos coma
				{
				$insertar_titulos.=",";
				$insertar_campos.=",";
				}
			}
			$sql="INSERT INTO `".$tabla."` ( ".$insertar_titulos." ) VALUES ( ".$insertar_campos." );";
			if(mysql_query($sql))
			{
			echo ". ";
			$registros++;
			}
			else
			{echo "X ";return false;}
		$linea++;
		}while(next($lineas));

	$sql="DELETE FROM `".$tabla."` WHERE 1".$sql_generado_para_eliminar;mysql_query($sql);
	echo "<br />";
	return $tabla;
	}
	else
	{
	return false;
	}
}

function quitar_extension($archivo)
{
	$extension = strrchr($archivo,".");
	$pos=strpos($archivo,$extension);
	return substr($archivo,0,$pos);
}


Código ejemplo de llamada / Code exmple call :

$tabla = exportarCSV_a_mySQL($_FILES['archivo_csv']);
if($tabla)
{
echo "Export OK in mysql table : ".$tabla;
}
else
{
echo "Error in export ...";
}

XML attributes to database columns

I recently needed to update a database with the contents of an XML file under a controlled environment (details at Blackrat's Blog) and came up with this.

With an XML input file of the following format
<tags>
  <tag name='test' desc='Test Description' other='Other Item' />
  <tag name='test2' desc='2nd Test Description' other='Another Item' />
</tags>


and a database which contains identical columns name,desc,other (or a superset of the tags) you can use the follow snippet to populate it.

View [import_xml.rhtml]
<h1>Import XML</h1>

<%= form_tag({ :action => 'import_xml'}, { :multipart => true }) %>
<%= file_field 'document', 'file' %>
<%= submit_tag 'Import' %>
<%= end_form_tag %>


Controller [names_controller.rb]
def import_xml
  require 'rexml/document'
  file=params[:document][:file]
  doc=REXML::Document.new(file.read)
  doc.root.each_element('//tag') do |tag|
    @name = Name.new
    @name.update_attributes(tag.attributes)
  end
  redirect_to :action => 'list'
end

The zen of python

An easter egg in python.
>>> import this
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
>>> 
« Newer Snippets
Older Snippets »
Showing 1-4 of 4 total  RSS