23 de diciembre de 2009 por Lucas Vieites
Para realizar una copia de seguridad de mis bases de datos MySQL solía hacer un «mysqldump» de todo lo que había en el servidor y comprimirlo en un «tar.gz». Esto me funcionó muy bien mientras tenía pocas bases de datos y las usaba todas con cierta frecuencia. Ahora tengo otras necesidades, ya que muchos de los proyectos asociados a esas bases de datos ya no están activos, los he transferido o, simplemente han muerto.
Para que me fuera más fácil poder restaurar solamente una base de datos, decidí modificar mi antiguo script para que volcara cada una de las bases de datos en un archivo distinto. Un par de horas después surgió esto:
#!/bin/bash
# Back up all databases of a server putting each db in a different file
# Backup destination directory
BACKUP_DIR="$HOME/backup/"
# Name of the backup file
BACKUP_FILENAME="mysqlbackup"
# Use the date for the filenames
BACKUP_DATE=`date +"%Y%m%d_%H%M%S"`
# Name of the archive file
BACKUP_ARCHIVE=${BACKUP_DIR}${BACKUP_FILENAME}_${BACKUP_DATE}.tgz
TEMP_DIR="/tmp/"
# Check if the temporary directory exists, if not, create it
if [ -d ${TEMP_DIR}${BACKUP_FILENAME}/ ]; then
# directory exists
echo "Cleaning ${TEMP_DIR} ..."
rm -rf ${TEMP_DIR}${BACKUP_FILENAME}/*
else
echo "Creating ${TEMP_DIR} ..."
mkdir ${TEMP_DIR}${BACKUP_FILENAME}/
fi
# Get all database names
DATABASES=`mysqlshow -u root -pmysqlpassword | sed 's/[ +-|]\+//g' | sed '/\-/d' | sed 's/^Databases//g' | sed '/^$/d'`
# Dump each db in a different file in the temp dir
for db in $DATABASES; do
echo item: $db
mysqldump -v -u root -pmysqlpassword -h localhost --create-options --extended-insert --databases $db > ${TEMP_DIR}${BACKUP_FILENAME}/${BACKUP_DATE}_${db}.sql
done
# Create the archive file in the backup dir
pushd ${TEMP_DIR}
tar cfz ${BACKUP_ARCHIVE} ${BACKUP_FILENAME}/${BACKUP_DATE}_*
popd
# Remove temp files
echo "Cleaning ${TEMP_DIR} ..."
rm -rf ${TEMP_DIR}${BACKUP_FILENAME}/*
# Pretty output
echo "###############################################################################"
echo " Archive file: ${BACKUP_ARCHIVE}"
echo " Archive size: "`stat -c%s ${BACKUP_ARCHIVE}`" bytes"
echo "###############################################################################"
echo "End"
echo ""
Creo se explica solo.
Los más vagos lo podéis descargar aquí: mysqlbackup.sh.txt.
No olvidéis darle permisos de ejecución («chmod +x nombre_de_archivo»), cambiar el nombre de usuario y la contraseña en los comandos «mysqlshow» y «mysqldump» y quitarle la extensión «.txt», aunque esto último es opcional.
14 de diciembre de 2009 por Lucas Vieites
Función en php para crear un menú desplegable con la etiqueta "select".
/**
* put_select returns a string with a filled <select> html form item
* @name the name of the form object
* @array_values a "key, value" type array with the values for the form item
* @marked string containing the default delected value
* @extra string with extra data for the "select" tag, such as javascript events like "onfocus" etc.
* @return string containing an html <select> tag
*/
function put_select($name, $array_values, $marked="", $extra="") {
$string = "";
// Only create the item if the values are in an array
if (is_array($array_values)) {
$string .= '<select name="'.$name.'" '.$extra.'>'."\n";
$string .= '<option value="--">---</option>'."\n";
while (list($key, $value) = each($array_values)) {
$string .= "<option value=\"".$key."\"";
if ($key == $marked) {
// The default selected item
$string .= " selected";
}
$string .= ">".$value."</option>\n";
}
$string .= "</select>\n";
} else {
// Return an error string
$string .= "ax_put_select() - Error 2002";
}
return $string;
}
Ejemplo de uso:
include 'functions.php'; // Aquí esta la función put_select
// bla bla bla ... html form etc.
$meses = array(
"01"=>"Enero",
"02"=>"Febrero",
"03"=>"Marzo",
"04"=>"Abril",
"05"=>"Mayo",
"06"=>"Junio",
"07"=>"Julio",
"08"=>"Agosto",
"09"=>"Septiembre",
"10"=>"Octubre",
"11"=>"Noviembre",
"12"=>"Diciembre"
);
$mes_por_defecto = date("m"); // Mes por defecto es el mes actual
print('Seleccione un mes: '.
put_select("losmeses", $meses, $mes_por_defecto, "onUnFocus=\"alert('Gracias!')\";")
.'<br/>');
Generará este código HTML:
Seleccione un mes: <select name="losmeses" onUnFocus="alert('Gracias!')";>
<option value="--">---</option>
<option value="01">Enero</option>
<option value="02">Febrero</option>
<option value="03">Marzo</option>
<option value="04">Abril</option>
<option value="05">Mayo</option>
<option value="06">Junio</option>
<option value="07">Julio</option>
<option value="08">Agosto</option>
<option value="09">Septiembre</option>
<option value="10">Octubre</option>
<option value="11">Noviembre</option>
<option value="12" selected>Diciembre</option>
</select>
<br/>
11 de diciembre de 2009 por Lucas Vieites
Función utilizada para mostrar el valor de una variable. Normalmente la uso para depurar el código.
/**
* debug; Prints a string and a variable value in red (for debugging purposes).
* @name string containing the name of the variable
*/
function debug($name) {
global ${$name};
global $debug;
$the_style = "color:#f00;font-weight:bold;";
// Only show output if debugging is on
if ($debug == 1) {
$var = ${$name};
if (is_array($var)) {
echo "##<b class=\"bold\">$name</b><br>\n";
while (list($key, $value) = each($var)){
print("\n".'<div style="'.$the_style.'">#=>'.$key.' ==> ');
if (is_array($value)){
print('<code>');
print_r($value);
print('</code>');
} else {
echo nl2br($value);
}
print('</div>'."\n");
}
} else {
print('<div style="'.$the_style.'">#'.$name.'=>'.$var.'#</div>'."\n");
}
}
}
Ejemplo de uso:
<?php
$debug = 1;
// ...
$mi_mensaje = "Mola Hundo!";
debug("mi_mensaje"); // OJO, se pone el _nombre_ de la variable, no la variable
// ...
?>