Vacaciones
for ($i=0; $i<1814400; $i++) {
echo "No hacer nada\n";
sleep(1);
}
for ($i=0; $i<1814400; $i++) {
echo "No hacer nada\n";
sleep(1);
}
Mi amigo Christian me ha comentado que la entrada anterior sobre Twitter sería más interesante si mostrara los datos sobre un término.
Pues dicho y hecho, tan sólo se necesitan dos scripts, uno para recuperar los datos y otro para mostrarlos. El primero habrá que ponerlo en el cron para que recupere los datos cada cierto tiempo (en mi ejemplo busco “google” cada 2 minutos).
Hay que tener cuidado porque Twitter da un máximo de 2000 actualizaciones nuevas, por lo que tendremos que ajustar los tiempos de consulta en Twitter.
El script que lee los datos es el siguiente:
<? php
function insertar($consulta, $ult) {
global $db;
$data = json_decode(file_get_contents('http://search.twitter.com/search?q='.urlencode($consulta).'&refresh=true&since_id='.$ult));
$n = isset($data->total) && $ult != $data->max_id? $data->total:0;
$db->queryExec('INSERT INTO estadisticas (fecha, n) values ('.time().', '.$n.')');
if (!$ult) $db->queryExec("INSERT INTO opciones (clave, valor) values ('ultimo', ".$data->max_id.")");
else $db->queryExec("UPDATE opciones SET valor = ".$data->max_id." where clave='ultimo' ");
}
$consulta = $_GET['q'];
// Limpio para poder usarlo en el nombre para la BD
$_consulta = preg_replace('/[^A-Z0-9]/i', '_', $consulta);
if ($db = new SQLiteDatabase($_consulta.'.db')) {
$q = @$db->query("SELECT valor FROM opciones Where clave='ultimo'");
if (!$q) {
$db->queryExec('CREATE TABLE estadisticas (fecha real, n real, PRIMARY KEY (fecha));');
$db->queryExec('CREATE TABLE opciones (clave text, valor text, PRIMARY KEY (clave));');
$q = $db->query("SELECT valor FROM opciones Where clave='ultimo'");
}
$r = $q->fetchAll(SQLITE_ASSOC);
$ult = 0;
if (!empty($r)) $ult = $r[0]['valor'];
insertar($consulta, $ult);
}
?>
Y el script que dibuja la gráfica es:
<? php
$desde = strtotime($_GET['desde']);
$hasta = strtotime($_GET['hasta']);
$consulta = $_GET['q'];
// Limpio para poder usarlo en el nombre para la BD
$_consulta = preg_replace('/[^A-Z0-9]/i', '_', $consulta);
if ($db = new SQLiteDatabase($_consulta.'.db')) {
$q = $db->query("SELECT fecha, n FROM estadisticas Where fecha>".$desde." and fecha<".$hasta);
$r = $q->fetchAll(SQLITE_ASSOC);
foreach($r as $item) {
$x[] = $item['n'];
$l[] = $item['fecha'];
}
}
header('Location: http://chart.apis.google.com/chart?chtt=Line+Chart&chts=000000,12&chs=1000x600&chf=bg,s,ffffff|c,s,ffffff&chxt=x,y&chxl=0:|'.implode('|', $l).'|1:|'.implode('|', $x).'&cht=lc&chd=t:75.00,16.66,0.00,8.33,100.00&chdl=Label+1&chco=0000ff&chls=1,1,0');
Actualización: Google Charts no deja meter muchos valores por lo que la gráfica de arriba sólo saca las 20 últimas actualizaciones
Interesantes consejos para optimizar nuestra base de datos en nuestras aplicaciones:
Una lectura interesante y más detallada.
Buen ejemplo para obtener la URL que nos dibuja gráficas usando Google Graph mediante procedimientos almacenados de MySQL. Está sacado de este ejemplo, que a su vez está sacado de este otro para Oracle.
DELIMITER $$
DROP FUNCTION IF EXISTS `dm_midas`.`FNC_GOOGRAPH_DB_SIZE`$$
CREATE FUNCTION `dm_midas`.`FNC_GOOGRAPH_DB_SIZE` (
p_chart_type CHAR,
p_height INT,
p_width INT) RETURNS varchar(3000) CHARSET latin1
READS SQL DATA
BEGIN
/* Author: Walter Heck - OlinData */
/* Date: 20090216 */
/* Note: After an idea by Alex Gorbachev - Pythian */
/* http://www.pythian.com/blogs/1490/google-charts-for-dba-tablespaces-allocation */
/* variable declaration */
DECLARE v_done BOOLEAN default false;
DECLARE v_url varchar(3000);
DECLARE v_schema_name varchar(3000);
DECLARE v_data_length_sum int;
DECLARE v_data_length_total int;
DECLARE v_legend_labels varchar(3000);
DECLARE v_chart_labels varchar(3000);
DECLARE v_chart_data varchar(3000);
/* Cursor declaration */
DECLARE c_schema_sizes cursor for
select
t.table_schema,
round(sum(t.data_length + t.index_length) / 1024 / 1024) as data_length_schema
from
information_schema.tables t
group by
t.table_schema
order by
t.table_schema;
/* Handler declaration */
DECLARE CONTINUE HANDLER FOR NOT FOUND SET v_done = true;
/* Initialize the variables */
SET v_legend_labels = '';
SET v_chart_labels = '';
SET v_chart_data = '';
/* Get the total data length + index_length for all tables */
select
round(sum(t.data_length + t.index_length) / 1024 / 1024) as data_length_total
into
v_data_length_total
from
information_schema.tables t;
/* Open the cursor */
OPEN c_schema_sizes;
/* Loop through the cursor */
get_data: LOOP
/* Fetch the next row of data into our variables */
FETCH c_schema_sizes INTO v_schema_name, v_data_length_sum;
/* if there is no more data, v_done will be true */
IF v_done THEN
/* Exit the loop */
LEAVE get_data;
END IF;
/* Add the schema name to the labels for the legend */
IF v_legend_labels = '' THEN
SET v_legend_labels = v_schema_name;
ELSE
SET v_legend_labels = concat(v_legend_labels, '|', v_schema_name);
END IF;
/* Add the total size of the schema to the labels */
IF v_chart_labels = '' THEN
SET v_chart_labels = v_data_length_sum;
ELSE
SET v_chart_labels = concat(v_chart_labels, '|', v_data_length_sum);
END IF;
/* Get the percentage of the total size as the graph's data */
IF v_chart_data = '' THEN
SET v_chart_data = ROUND(v_data_length_sum / v_data_length_total, 2) * 100;
ELSE
SET v_chart_data = concat(v_chart_data, ',', ROUND(v_data_length_sum / v_data_length_total, 2) * 100);
END IF;
END LOOP get_data;
/* Close the cursor */
CLOSE c_schema_sizes;
/* Build up the google graph url */
SET v_url = 'http://chart.apis.google.com/chart?';
SET v_url = CONCAT(v_url, 'cht=', p_chart_type);
SET v_url = CONCAT(v_url, '&chs=', p_width , 'x', p_height);
SET v_url = CONCAT(v_url, '&chtt=Database Sizes (MB)');
SET v_url = CONCAT(v_url, '&chl=', v_chart_labels);
SET v_url = CONCAT(v_url, '&chd=t:', v_chart_data);
SET v_url = CONCAT(v_url, '&chdl=', v_legend_labels);
/* return the url as the function's result */
RETURN v_url;
END$$
DELIMITER ;