Skip to content

Instantly share code, notes, and snippets.

@jpolvora
Last active Sep 7, 2018
Embed
What would you like to do?
<?php
include '../funcoes.php';
include '../conecta.php';
function insert(&$insert_fields)
{
$insert_sql = 'INSERT INTO fases '
.' ('.implode(', ', array_keys($insert_fields)).')'
.' VALUES ('.implode(', ', array_values($insert_fields)).')';
mysql_query($insert_sql) or die(mysql_error());
}
function execute($sql, ...$args)
{
$formatted = isset($args)
? sprintf($sql, ...$args)
: $sql;
$result = mysql_query($formatted) or die(mysql_error());
$retorno = [];
if (!is_bool($result)) {
while ($row = mysql_fetch_assoc($result)) {
array_push($retorno, $row);
}
mysql_free_result($result);
}
return $retorno;
}
function quote($val)
{
return "'".$val."'";
}
function take(&$inscricoes, $uf)
{
reset($inscricoes);
if (empty($uf)) {
return array_shift($inscricoes);
}
while (list($key, $val) = each($inscricoes)) {
if ($val['uf'] != $uf) {
return array_shift($inscricoes);
}
}
return array_shift($inscricoes);
}
execute('truncate table fases');
$categorias = execute('SELECT id_categoria, COUNT(*) as total FROM inscricoes GROUP BY id_categoria');
$count_categorias = count($categorias);
$count_inserted = 0;
$sum = 0;
$lastuf = '';
for ($i = 0; $i < $count_categorias; ++$i) {
$categoria = intval($categorias[$i]['id_categoria']);
if (empty($categoria)) {
continue;
}
$inscricoes = execute('select id_inscricao, nome, equipe, uf from inscricoes where id_categoria = %d order by rand()', $categoria);
printf("Qtde de inscrições para a categoria '%s' : %d\n", $categoria, count($inscricoes));
$sum += count($inscricoes);
while (count($inscricoes) > 0) {
$inscricao = take($inscricoes, $lastuf);
if (empty($inscricao)) {
continue;
}
//verifica se já foi inserido
$count = execute('select count(*) as total from fases where fase = 1 and id_categoria = %d and id_inscricao = %d', $categoria, $inscricao['id_inscricao']);
if ($count[0]['total'] > 0) {
//die('Não pode duplicar');
continue;
}
$insert_fields = array(
'id_inscricao' => intval($inscricao['id_inscricao']),
'nome' => quote($inscricao['nome']),
'uf' => quote($inscricao['uf']),
'equipe' => quote($inscricao['equipe']),
'id_categoria' => $categoria,
'fase' => 1,
);
insert($insert_fields);
++$count_inserted;
$lastuf = $inscricao['uf'];
printf("Restando: %d\n", count($inscricoes));
}
echo "==================================\n";
}
printf('fim do processamento: %d registros inseridos!, %d retornados', $count_inserted, $sum);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment