Activar la opción de trabajar con tablas vinculadas en PhpMyAdmin

PhpMyAdmin incluye opciones para relacionar tablas (de tipo InnoDB), pero muchas veces vienen desactivadas y al darle al boton operaciones en la base de datos, aparece el error: Las opciones adicionales para trabajar con tablas vinculadas fueron desactivadas. Para saber porqué, dé clic aquí.

Para activarlas debemos añadir algunas opciones a los ficheros de configuración del PMA.

En algunos paquetes que integran Apache, MySQL y PHP no es necesario configurar nada porque ya traen activadas por defecto estas opciones, comoXAMPP. En otros paquetes, aunque configures estas opciones, es posible que sigan sin funcionar las relaciones, como en el WAMP.

Para lograr que funcionen las relaciones debemos seguir estos pasos:

  1. Comprobar si tenemos una tabla llamada phpmyadmin. Si no es así, ejecutar el script create_tables.sql, que está en la carpeta de scripts de phpmyadmin.
    Esta es una tabla que usa PMA internamente para ofrecer características adicionales, como las relaciones entre tablas.
  2. Acceder al fichero de configuración de PMA config.inc.php (en las versiones nuevas viene como config.default.php) y dejar estas opciones tal y como se indica a continuación:
    $cfg['Servers'][$i]['auth_type'] = 'http';
    $cfg['Servers'][$i]['controluser'] = 'pma';
    $cfg['Servers'][$i]['controlpass'] = 'pmapass';
    $cfg['Servers'][$i]['pmadb'] = 'phpmyadmin';
    $cfg['Servers'][$i]['bookmarktable'] = 'pma_bookmark';
    $cfg['Servers'][$i]['relation'] = 'pma_relation';
    $cfg['Servers'][$i]['table_info'] = 'pma_table_info';
    $cfg['Servers'][$i]['table_coords'] = 'pma_table_coords';
    $cfg['Servers'][$i]['pdf_pages'] = 'pma_pdf_pages';
    $cfg['Servers'][$i]['column_info'] = 'pma_column_info';
    $cfg['Servers'][$i]['history'] = 'pma_history';
    $cfg['Servers'][$i]['designer_coords'] = 'pma_designer_coords';
  3. Crear un usuario MySQL para utilizar la relación entre tablas (que será el que indicamos anteriormente como controluser con la contraseña indicada en controlpass) y asignarle los correspondientes permisos:
    GRANT USAGE ON mysql.* TO 'pma'@'localhost' IDENTIFIED BY 'pmapass';
    GRANT SELECT (Host, User, Select_priv, Insert_priv, Update_priv, Delete_priv, Create_priv, Drop_priv, Reload_priv, Shutdown_priv, Process_priv, File_priv, Grant_priv, References_priv, Index_priv, Alter_priv, Show_db_priv, Super_priv, Create_tmp_table_priv, Lock_tables_priv, Execute_priv, Repl_slave_priv, Repl_client_priv) ON mysql.user TO 'pma'@'localhost';
    GRANT SELECT ON mysql.db TO 'pma'@'localhost';
    GRANT SELECT ON mysql.host TO 'pma'@'localhost';
    GRANT SELECT (Host, Db, User, Table_name, Table_priv, Column_priv) ON mysql.tables_priv TO 'pma'@'localhost';
  4. Reiniciar apache y acceder al PMA. Si todo ha salido bien, ya no tendremos el mensaje de error y aparecerá en el menú de arriba el botón diseñador, desde donde podremos establecer las relaciones entre tablas.

Más información:
PhpMyAdmin Wiki

Script para optimizar las tablas fragmentadas en MySQL

Bueno otro buen script a la huchaca… esta escrito en bash aparte de ser utilisisimo porque chequea las tablas fragmentadas y tambien chequea todas las bbdds en busca de tablas MyISAM o INNODB y las optimiza.

#!/bin/bash

VERSION="0.7.2"
log="$PWD/mysql_error_log.txt"

echo "MySQL fragmentation finder (and fixer) v$VERSION, written by Phil Dufault ( http://www.dufault.info/ )"

showHelp() {
echo -e "\tThis script only repairs MyISAM and InnoDB tables"
echo -e "\t--help or -h\t\tthis menu"
echo -e "\t--user username\tspecify mysql username to use\n\t\t\tusing this flag means the script will ask for a password during runtime, unless you supply..."
echo -e "\t--password \"yourpassword\""
echo -e "\t--host hostname\tspecify mysql hostname to use, be it local (default) or remote"
}

#s parse arguments
while [[ $1 == -* ]]; do
case "$1" in
--help|-h) showHelp; exit 0;;
--user) mysqlUser="$2"; shift 2;;
--password) mysqlPass="$2"; shift 2;;
--host) mysqlHost="$2"; shift 2;;
--) shift; break;;
esac
done

# prevent overwriting the commandline args with the ones in .my.cnf, and check that .my.cnf exists
if [[ ! $mysqlUser && -f "$HOME/.my.cnf" ]]; then
if grep "user=" "$HOME/.my.cnf" >/dev/null 2>&1; then
if grep "pass=" "$HOME/.my.cnf" >/dev/null 2>&1; then
mysqlUser=$(grep user= < "$HOME/.my.cnf" | awk -F\" '{print $2}'); mysqlPass=$(grep pass= < "$HOME/.my.cnf" | awk -F\" '{print $2}'); if grep "host=" "$HOME/.my.cnf" >/dev/null 2>&1; then
mysqlHost=$(grep host= < "$HOME/.my.cnf" | awk -F\" '{print $2}'); fi else echo "Found no pass line in your .my.cnf,, fix this or specify with --password" fi else echo "Found no user line in your .my.cnf, fix this or specify with --user" exit 1; fi fi # set localhost if no host is set anywhere else if [[ ! $mysqlHost ]]; then mysqlHost="127.0.0.1" fi # error out if [[ ! $mysqlUser ]]; then echo "Authentication information not found as arguments, nor in $HOME/.my.cnf" echo showHelp exit 1 fi if [[ ! $mysqlPass ]]; then echo -n "Enter your MySQL password: " read -s mysqlPass fi # Test connecting to the database: mysql -u"$mysqlUser" -p"$mysqlPass" -h"$mysqlHost" --skip-column-names --batch -e "show status" >/dev/null 2>&1
if [[ $? -gt 0 ]]; then
echo "An error occured, check $log for more information.";
exit 1;
fi

# Retrieve the listing of databases:
databases=( $(mysql -u"$mysqlUser" -p"$mysqlPass" -h"$mysqlHost" --skip-column-names --batch -e "show databases;" 2>"$log") );
if [[ $? -gt 0 ]]; then
echo "An error occured, check $log for more information."
exit 1;
fi

echo -e "Found ${#databases[@]} databases";
for i in ${databases[@]}; do
# get a list of all of the tables, grep for MyISAM or InnoDB, and then sort out the fragmented tables with awk
fragmented=( $(mysql -u"$mysqlUser" -p"$mysqlPass" -h"$mysqlHost" --skip-column-names --batch -e "SHOW TABLE STATUS FROM $i;" 2>"$log" | awk '{print $1,$2,$10}' | egrep "MyISAM|InnoDB" | awk '$3 > 0' | awk '{print $1}') );
if [[ $? -gt 0 ]]; then
echo "An error occured, check $log for more information."
exit 1;
fi
tput sc
echo -n "Checking $i ... ";
if [[ ${#fragmented[@]} -gt 0 ]]; then
if [[ ${#fragmented[@]} -gt 0 ]]; then
if [[ ${#fragmented[@]} -gt 1 ]]; then
echo "found ${#fragmented[@]} fragmented tables."
else
echo "found ${#fragmented[@]} fragmented table."
fi
fi
for table in ${fragmented[@]}; do
let fraggedTables=$fraggedTables+1;
echo -ne "\tOptimizing $table ... ";
mysql -u"$mysqlUser" -p"$mysqlPass" -h"$mysqlHost" -D "$i" --skip-column-names --batch -e "optimize table $table" 2>"$log" >/dev/null
if [[ $? -gt 0 ]]; then
echo "An error occured, check $log for more information."
exit 1;
fi
echo done
done
else
tput rc
tput el
fi
unset fragmented
done

# footer message
if [[ ! $fraggedTables -gt 0 ]]; then
echo "No tables were fragmented, so no optimizing was done.";
else
if [[ $fraggedTables -gt 1 ]]; then
echo "$fraggedTables tables were fragmented, and were optimized.";
else
echo "$fraggedTables table was fragmented, and was optimized.";
fi
fi

if [[ ! -s $log ]]; then
rm -f "$log"
fi

unset fraggedTables

Link | http://www.dufault.info/blog/a-script-to-optimize-fragmented-tables-in-mysql/

Reparar todas las tablas de todas las bases de datos de MySQL en Plesk

Para reparar todas las tablas de todas las bases de datos de MySQL en Plesk (Linux) tenemos que poner en una sola linea este pedazo churro:

for database in $(mysql --skip-column-names -uadmin -p`cat /etc/psa/.psa.shadow` -e
"show databases" ); do echo "optmizing tables from $database";
for table in $(mysql --skip-column-names -uadmin -p`cat /etc/psa/.psa.shadow` -e
"show tables" $database ); do echo "-> $table " ;
mysql -uadmin -p`cat /etc/psa/.psa.shadow` -e "OPTIMIZE TABLE $table" $database ;
done ; done ;

Exportar tablas de base de datos MySQL en formato XML

A continuación os comento la necesidad que tenia un cliente nuestro para publicitar su tienda virtual en los distintos escaparates y webs como ciao.es, mercamania.com….etc… y  es que necesitaba exportar todos los prodcutos, familias y categorias, por separado a un formato xml y a una URL fija, pues bien como la base de datos tenia las tablas de productos, familias y categorias por separado, lo unico que hice fue un ejecutable para que exportase las tablas y este añadirlo a una tarea de cron que se ejecutara todos los dias a una hora y tal. Aqui os dejo el simple script.

Continuar leyendo «Exportar tablas de base de datos MySQL en formato XML»