Ir para conteúdo
Fórum Script Brasil
  • 0

Relatório demora demais para ser gerado


Felipe Schneider

Pergunta

Ola pessoal.
Estou com um problema bem interessante. Tenho um sistema PHP com MySQL muito antigo e um dos relatórios demora demais para ser gerado. Chega a levar em média 3 a 4 horas. Nunca me preocupei em melhorar isso, até mesmo porque não foi eu quem fiz o sistema. Mas agora, está me gerando problemas demais. Justamente porque o servidor de hospedagem que tenho o sistema, fez algumas atualizações e mudanças, inclusive no time_exception do PHP e meu sistema não consegue gerar o relatório por completo. Ele para no meio do caminho. O relatório é para fazer uma pesquisa entre um dia X e um dia Y e trazer algumas informações de exames realizados. O BD para consulta tem mais de 200mil linhas. Abaixo está o código da pesquisa. Se alguém puder me ajudar, agradeço demais!

<?php
if (file_exists("master.php")) { include("master.php"); }
else { include("../master.php"); echo "<link href='../master.css' rel='stylesheet' type='text/css' />"; }
?>
<table width="100%" border="0" style="border:1px solid #999999; background-color:#FFFFFF;">
<? if ($_POST['imprimir'] == "") { ?>
	<tr>
		<td>&nbsp;</td>
		<td align="right">
		<form method="post" action="relatorios/atendimento_empresa2.php">
			<input type="hidden" name="atendimento_empresa" value="<?=$_POST['atendimento_empresa'];?>" />
			<input type="hidden" name="atendimento_empresa_data_dia" value="<?=$_POST['atendimento_empresa_data_dia'];?>" />
			<input type="hidden" name="atendimento_empresa_data_mes" value="<?=$_POST['atendimento_empresa_data_mes'];?>" />
			<input type="hidden" name="atendimento_empresa_data_ano" value="<?=$_POST['atendimento_empresa_data_ano'];?>" />
			<input type="hidden" name="atendimento_empresa_data_ate_dia" value="<?=$_POST['atendimento_empresa_data_ate_dia'];?>" />
			<input type="hidden" name="atendimento_empresa_data_ate_mes" value="<?=$_POST['atendimento_empresa_data_ate_mes'];?>" />
			<input type="hidden" name="atendimento_empresa_data_ate_ano" value="<?=$_POST['atendimento_empresa_data_ate_ano'];?>" />

			<input type="hidden" name="imprimir" value="sim" />
			<input type="submit" value="imprimir" />
		</form>
		</td>
	</tr>
<? } ?>
<?php
if ($_POST['atendimento_empresa'] != 'todas') $where_init = ' WHERE id = "' . $_POST['atendimento_empresa'] . '"';
$empresas = mysql_query("SELECT * FROM empresas{$where_init} ORDER BY `razao`");
while($selecionar = @mysql_fetch_assoc($empresas)) {

$_dia = $_POST['atendimento_empresa_data_dia'];
$_mes = $_POST['atendimento_empresa_data_mes'];
$_ano = $_POST['atendimento_empresa_data_ano'];
$__dia = $_POST['atendimento_empresa_data_ate_dia'];
$__mes = $_POST['atendimento_empresa_data_ate_mes'];
$__ano = $_POST['atendimento_empresa_data_ate_ano'];
$where = "((ano > $_ano) OR ((ano = $_ano) AND (mes > $_mes)) OR ((ano = $_ano) AND (mes = $_mes) AND (dia >= $_dia))) AND ((ano < $__ano) OR ((ano = $__ano) AND (mes < $__mes)) OR ((ano = $__ano) AND (mes = $__mes) AND (dia <= $__dia)))";
$selecionar_cliente = mysql_query("SELECT * FROM clientes_old WHERE (id_emp = '".$selecionar['id']."') AND (opcao != 'ficha') AND ".$where." ORDER BY 'nome'");
if ((mysql_num_rows($selecionar_cliente) > "0") or ($_POST['atendimento_empresa'] != 'todas')) {
?>
	<tr>
		<td><center>
		<b>Hist&oacute;rico de exames da empresa <i><?=utf8_encode($selecionar['razao'])?></i> de <?=$_POST['atendimento_empresa_data_dia']?>/<?=$_POST['atendimento_empresa_data_mes']?>/<?=$_POST['atendimento_empresa_data_ano']?> at&eacute; <?=$_POST['atendimento_empresa_data_ate_dia']?>/<?=$_POST['atendimento_empresa_data_ate_mes']?>/<?=$_POST['atendimento_empresa_data_ate_ano']?></b>
		</center></td>
	</tr>
	<tr><td>&nbsp;</td></tr>
	<tr><td>
	<?
	if (mysql_num_rows($selecionar_cliente) <= "0") {
		echo "<tr><td>Sem hist&oacute;rico para esta empresa.</td></tr>";
	}
	else {
		$setores = array();
		while ($x = mysql_fetch_assoc($selecionar_cliente)) {
			if (!in_array(trim(strtr(strtoupper($x['setor']),"áéíóúâêôãõàèìòùç","ÁÉÍÓÚÂÊÔÃÕÀÈÌÒÙÇ")), $setores)) {
				$conta = "1";
				echo "<table width='100%' border=1>";
				echo "<tr><td width='5%'>&nbsp;</td><td width='45%'><b>Setor:</b> ".utf8_encode($x['setor'])."</td><td width='10%'></td><td width='10%'></td></tr>";
				echo "<tr><td width='5%'><center>&nbsp;</center></td><td width='45%'><center><b>Funcion&aacute;rio</b></center></td><td width='10%'><center><b>Data realiza&ccedil;&atilde;o</b></center></td><td width='10%'><center><b>Exames</b></center></td></tr>";


				$selecionar_adm = mysql_query("SELECT * FROM clientes_old WHERE (id_emp = '".$selecionar['id']."' and setor = '".$x['setor']."' and exame_clinico = 'Admissional' and opcao = 'aso') and ".$where);
				if (mysql_num_rows($selecionar_adm) > "0") {
					while ($y = mysql_fetch_assoc($selecionar_adm)) {
						echo "<tr><td width='5%'>".$conta."</td><td width='45%'>".utf8_encode($y['nome'])."</td><td width='10%'><center>".$y['dia']."/".$y['mes']."/".$y['ano']."</center></td><td width='10%'><center>".$y['exame_clinico']."</center></td></tr>";
						$conta++;
					}
				}


				$selecionar_dem = mysql_query("SELECT * FROM clientes_old WHERE (id_emp = '".$selecionar['id']."' and setor = '".$x['setor']."' and exame_clinico = 'Demissional' and opcao = 'aso') and ".$where);
				if (mysql_num_rows($selecionar_dem) > "0") {
					while ($y = mysql_fetch_assoc($selecionar_dem)) {
						echo "<tr><td width='5%'>".$conta."</td><td width='45%'>".utf8_encode($y['nome'])."</td><td width='10%'><center>".$y['dia']."/".$y['mes']."/".$y['ano']."</center></td><td width='10%'><center>".$y['exame_clinico']."</center></td></tr>";
						$conta++;
					}
				}


				$selecionar_per = mysql_query("SELECT * FROM clientes_old WHERE (id_emp = '".$selecionar['id']."' and setor = '".$x['setor']."' and exame_clinico = 'Periódico' and opcao = 'aso') and ".$where);
				if (mysql_num_rows($selecionar_per) > "0") {
					while ($y = mysql_fetch_assoc($selecionar_per)) {
						echo "<tr><td width='5%'>".$conta."</td><td width='45%'>".utf8_encode($y['nome'])."</td><td width='10%'><center>".$y['dia']."/".$y['mes']."/".$y['ano']."</center></td><td width='10%'><center>".utf8_encode($y['exame_clinico'])."</center></td></tr>";
						$conta++;
					}
				}


				$selecionar_ret = mysql_query("SELECT * FROM clientes_old WHERE (id_emp = '".$selecionar['id']."' and setor = '".$x['setor']."' and exame_clinico = 'Retorno ao Trabalho' and opcao = 'aso') and ".$where);
				if (mysql_num_rows($selecionar_ret) > "0") {
					while ($y = mysql_fetch_assoc($selecionar_ret)) {
						echo "<tr><td width='5%'>".$conta."</td><td width='45%'>".utf8_encode($y['nome'])."</td><td width='10%'><center>".$y['dia']."/".$y['mes']."/".$y['ano']."</center></td><td width='10%'><center>".$y['exame_clinico']."</center></td></tr>";
						$conta++;
					}
				}


				$selecionar_mud = mysql_query("SELECT * FROM clientes_old WHERE (id_emp = '".$selecionar['id']."' and setor = '".$x['setor']."' and exame_clinico = 'Mudança Função' and opcao = 'aso') and ".$where);
				if (mysql_num_rows($selecionar_mud) > "0") {
					while ($y = mysql_fetch_assoc($selecionar_mud)) {
						echo "<tr><td width='5%'>".$conta."</td><td width='45%'>".utf8_encode($y['nome'])."</td><td width='10%'><center>".$y['dia']."/".$y['mes']."/".$y['ano']."</center></td><td width='10%'><center>".utf8_encode($y['exame_clinico'])."</center></td></tr>";
						$conta++;
					}
				}

				$selecionar_audio = mysql_query("SELECT * FROM clientes_old WHERE (id_emp = '".$selecionar['id']."' and setor = '".$x['setor']."' and opcao = 'audio') and ".$where);
				if (mysql_num_rows($selecionar_audio) > "0") {
					while ($y = mysql_fetch_assoc($selecionar_audio)) {
						echo "<tr><td width='5%'>".$conta."</td><td width='45%'>".utf8_encode($y['nome'])."</td><td width='10%'><center>".$y['dia']."/".$y['mes']."/".$y['ano']."</center></td><td width='10%'><center>Audiometria</center></td></tr>";
						$conta++;
					}
				}

				$selecionar_ficha = mysql_query("SELECT * FROM clientes_old WHERE (id_emp = '".$selecionar['id']."' and setor = '".$x['setor']."' and opcao = 'atendimento') and ".$where);
				if (mysql_num_rows($selecionar_ficha) > "0") {
					while ($y = mysql_fetch_assoc($selecionar_ficha)) {
						echo "<tr><td width='5%'>".$conta."</td><td width='45%'>".utf8_encode($y['nome'])."</td><td width='10%'><center>".$y['dia']."/".$y['mes']."/".$y['ano']."</center></td><td width='10%'><center>Atend. cl&iacute;nico</center></td></tr>";
						$conta++;
					}
				}

				$selecionar_comp = mysql_fetch_assoc(mysql_query("SELECT * FROM empresas_setores WHERE id_emp = '".$x['id_emp']."' AND setor = '".$x['setor']."' AND funcao = '".$x['funcao']."' LIMIT 1"));
				$selecionar_exames = mysql_query("SELECT * FROM clientes_old WHERE (id_emp = '".$selecionar['id']."' and setor = '".$x['setor']."' and exames != '' and exames_feed != 'ausente' and opcao = 'aso') and ".$where);
				if (mysql_num_rows($selecionar_exames) > "0") {
					while ($y = mysql_fetch_assoc($selecionar_exames)) {
						echo "<tr><td width='5%'>".$conta."</td><td width='45%'>".utf8_encode($y['nome'])."</td><td width='10%'><center>".$y['dia']."/".$y['mes']."/".$y['ano']."</center></td><td width='10%'><center>".utf8_encode($y['exames'])."</center></td></tr>";
						$conta++;
					}
				}

				echo "</table><br>";
				$setores[] = trim(strtr(strtoupper($x['setor']),"áéíóúâêôãõàèìòùç","ÁÉÍÓÚÂÊÔÃÕÀÈÌÒÙÇ"));
			}
		}
	}
}
echo '</td></tr>';
}
	?>
	</td></tr>

</table>
<?php if ($_POST['imprimir'] != "") { echo "<script>window.print(); history.back();</script>"; } ?>

 

Link para o comentário
Compartilhar em outros sites

1 resposta a esta questão

Posts Recomendados

  • 0

Verifique se a tabela empresas possui indices para os campos id e razão (um índice para cada campo)
tabela clientes_old possui indices para campos id_emp,opcao,ano,mes,dia (um indice para todos estes campos)
Se a tabela clientes_old for muito grande, verifique, também, se há indice para o campo nome 
tabela clientes_old possui indices para campos id_emp,setor,exame_clinico,opcao,ano,mes,dia (um indice para todos estes campos)
tabela empresas_setores id,setor,funcao (um indice para todos estes campos)

 

Rode cada um dos selects, dentro do phpadmin ou outro sgbd, com a palavra EXPLAIN antes da palavra SELECT e poste o resultado se as ações acima não melhorarem o tempo de execução de seu relatório.

Link para o comentário
Compartilhar em outros sites

Participe da discussão

Você pode postar agora e se registrar depois. Se você já tem uma conta, acesse agora para postar com sua conta.

Visitante
Responder esta pergunta...

×   Você colou conteúdo com formatação.   Remover formatação

  Apenas 75 emoticons são permitidos.

×   Seu link foi incorporado automaticamente.   Exibir como um link em vez disso

×   Seu conteúdo anterior foi restaurado.   Limpar Editor

×   Você não pode colar imagens diretamente. Carregar ou inserir imagens do URL.



  • Estatísticas dos Fóruns

    • Tópicos
      152,1k
    • Posts
      651,9k
×
×
  • Criar Novo...