Hi,
Thanks for your reply. In fact, I tried with session but when trying to navigate to another page there seems to be a bug here and I cant discover it. 🙁
If it isn't to much, and since you seem to be quite confortable with sessions, could yould just give a slight look at this? Thanks in advance.
(This is just the test page)
<!---### THE CODE ###--->
<?
include("../admin/includes/database.php");
function getRowFromPage($page)
{
// devolve a $lastr da página $page
// page: o número da página
global $lastr;
return ($page*$lastr)-$lastr;
}
// Session functions firstr=10&lastr
// Manter os critérios da pesquisa quando se navega pelos resultados.
session_name("mywebsite");
session_start();
if(!session_is_registered("mywebsite_search")){
$mywebsite_search = "last_search";
session_register( "mywebsite_search" );
$copy_postvars=$HTTP_POST_VARS;
session_register( "copy_postvars" );
} else {
if(!isset($copy_postvars)) $copy_postvars=$HTTP_POST_VARS;
}
foreach($copy_postvars as $key => $value){
$$key=$value;
}
//dp($HTTP_SESSION_VARS,"");
if($last==1){
if($mywebsite_lastSearch=="detalhada"){ //A última pesquisa efectuada é detalhada?
foreach($copy_getvars as $key => $value) $$key=$value; //sacar variáveis de sort armazenadas
} else {
$mywebsite_lastSearch="detalhada";
session_register("mywebsite_lastSearch");
$firstr=0;
$lastr=10;
$copy_getvars["firstr"]=0;
$copy_getvars["lastr"]=10;
session_register("copy_getvars");
exit;
}
} else { //pesquisa detalhada normal
$mywebsite_lastSearch="detalhada";
session_register("mywebsite_lastSearch");
$copy_getvars=$HTTP_GET_VARS;
session_register("copy_getvars");
}
/////////////////////////////////////////////////////////////
//
// Pesquisar Empreendimentos por Dados Gerais
//
//
/////////////////////////////////////////////////////////////
//Inicia a contagem de tempo de execução do script
$mtime = microtime();
$mtime = explode(" ",$mtime);
$mtime = $mtime[1] + $mtime[0];
$starttime = $mtime;
?>
<!---### START HTML ###--->
<?
//Garante o display do formulário e retira-o após o SUBMIT
if($action=="pesquisar"){
?>
<!---### START FORMULÁRIO ###--->
<font face="Arial" size="5"><b>Pesquisa Detalhada por Empreendimento e Localização</b></font><br>
<font face="Verdana" size="2">Deve seleccionar pelo menos um elemento para além da localização</font><br>
<FORM METHOD="post" ACTION="<? echo $PHP_SELF; ?>" name="pesquisar">
<font face="Verdana" size="2">Nome do empreendimento</font> <input type="text" name="nome" size="20">
<font face="Verdana" size="2">Morada</font> <input type="text" name="morada" size="20">
<font face="Verdana" size="2">Código Postal</font> <input type="text" name="cp1" size="4" maxlength="4"><br>
<font face="Verdana" size="2">Telefone</font> <input type="text" name="telunique" size="6" maxlength="9">
<font face="Verdana" size="2">Fax</font> <input type="text" name="faxunique" size="6" maxlength="9">
<font face="Verdana" size="2">E-mail</font> <input type="text" name="email" size="15"><br>
<font face="Verdana" size="2">Director</font> <input type="text" name="director" size="20">
<font face="Verdana" size="2">Chefe de Reservas <input type="text" name="chefersv" size="20">
<br><font face="Verdana" size="2"> Classificação de empreendimento :</font>
<SELECT NAME="f[classID]">
<OPTION VALUE="Qualquer">Qualquer</OPTION>
<?
// Selleciona os tipos de alojamento e actualiza sempre que
// é adicionado um distrito
$query = "SELECT FROM classificacoes WHERE class_descr IS NOT NULL ORDER BY class ASC LIMIT 0,6";
$result = mysql_query($query);
while($rowCL = mysql_fetch_array($result)){
echo '<OPTION VALUE="'.$rowCL['classID'].'" ';
// Guarda o distrito da pesquisa anterior se for encontrado um
if($rowCL['classID'] == $f['classID']){
echo ' SELECTED ';
}
echo '>'.$rowCL['class'].'</OPTION>'."\n";
}
?>
</SELECT> Palavras na descrição :</font>
<input type="text" name="descricao" size="20"><br>
<font face='Verdana' size=2>Localização:
<SELECT NAME="f[distrito]">
<OPTION VALUE="Qualquer">Qualquer</OPTION>
<?
// Selleciona os Distritos e actualiza sempre que
// é adicionado um distrito
$query = "SELECT FROM distritos";
$result = mysql_query($query);
while($rowD = mysql_fetch_array($result)){
echo '<OPTION VALUE="'.$rowD['ID'].'" ';
// Guarda o distrito da pesquisa anterior se for encontrado um
if($rowD['ID'] == $f['distrito']){
echo ' SELECTED ';
$haconcelho="<b>Pode seleccionar também um concelho.</b><br>";
}
echo '>'.$rowD['distrito'].'</OPTION>'."\n";
}
?>
</SELECT> na ilha de
<SELECT NAME="f[ilha]">
<OPTION VALUE="Qualquer">Qualquer</OPTION>";
<?
// get all of our categories - updated whenever a
// distrito is added
//Verifica se é ou não uma ilha e coloca o AND clause
if($f['distrito'] != '1' || $f['distrito'] != '13'){
} else {
$AND = ' ilha_ID='.$f['ilha'].' AND ';
}
$query = "SELECT FROM ilhas WHERE $AND distrito_ID='".$f['distrito']."'";
$result = mysql_query($query);
while($rowI = mysql_fetch_array($result)){
echo '<OPTION VALUE="'.$rowI['ID'].'" ';
// Guarda a Ilha da pesquisa anterior se for encontrado um
if($rowI['ID'] == $f['ilha']){
echo ' SELECTED ';
}
echo '>'.$rowI['ilha'].'</OPTION>'."\n";
}
?>
</SELECT> no concelho de
<SELECT NAME="c[concelho]">
<OPTION VALUE="Qualquer">Qualquer</OPTION>
<?
//Verifica se é ou não uma ilha e coloca o AND clause
if($f['distrito'] != '1' && $f['distrito'] != '13'){
$AND =' distrito_ID='.$f['distrito'].'';
} else {
$heilha="Seleccionou um arquipélago.<br><b>Pode seleccionar agora uma ilha.</b><br> ";
$AND = ' ilha_ID='.$f['ilha'].'';
}
// Selleciona os Concelhos e actualiza sempre que
// é adicionado um Concelho
$query = "SELECT FROM concelhos WHERE $AND";
$result = mysql_query($query);
while($rowC = mysql_fetch_array($result)){
echo '<OPTION VALUE="'.$rowC['ID'].'" ';
// Guarda o distrito da pesquisa anterior se for encontrado um
if($rowC['ID'] == $c['concelho']){
echo ' SELECTED ';
}
echo '>'.$rowC['concelho'].'</OPTION>'."\n";
}
?>
<script>
function checkifempty(){
if ((document.pesquisar.nome.value.length<3) && (document.pesquisar.morada.value=='') && (document.pesquisar.cp1.value=='') && (document.pesquisar.director.value=='') && (document.pesquisar.chefersv.value=='') && (document.pesquisar.descricao.value=='') && (document.pesquisar.telunique.value.length<3) && (document.pesquisar.faxunique.value.length<3) && (document.pesquisar.email.value.length<5))
document.pesquisar.submit.disabled=true
else
document.pesquisar.submit.disabled=false
}
if (document.pesquisar)
setInterval("checkifempty()",100)
</script>
</SELECT><br>
Quero ver apenas um número de resultados entre
<INPUT TYPE="text" VALUE="<? echo $f['record_start']; ?>" NAME="f[record_start]" SIZE="2" maxlength="3"> e
<INPUT TYPE="text" VALUE="<? echo $f['record_limit']; ?>" NAME="f[record_limit]" SIZE="2" maxlength="3">
<br><a href="pesquisar_emprc.php">Pesquisar por Características</a>
<P><?= $heilha ?><?= $haconcelho ?>
<INPUT TYPE="reset" NAME="reset" VALUE="Apagar selecções">
<INPUT TYPE="submit" NAME="submit" VALUE="Procurar!">
</FORM></font>
<!---### END FORMULÁRIO ###--->
<? } ?>
<!---### START MAIN PHP CODING ###--->
<?
////////////////////////////////////////////////////////////////////////////////////////
//Após o SUBMIT inícia o PHP e apresenta os resultados sem o formulário
if(isset($submit)){
//Verifica a necessidade de procurar noutras tabelas
if($f['concelho']!=='Qualquer'){
$tabela_concelhos="concelhos AS C";
}
if($f['ilha']!=='Qualquer'){
$tabela_ilhas=" ilhas AS IL,";
}
// Se a CLASSIFICAÇÃO diferente de "Qualquer" então adiona o WHERE
if($f['classID'] != 'Qualquer'){
$where[] = ' E.class_ID='.$f['classID'].' ';
}
// Query inicial onde serão adicionados os array "where"
$query = "SELECT DISTINCT(empr), E.* FROM empreendimentos AS E, distritos AS D, $tabela_ilhas $tabela_concelhos";
//Se seleccionou NOME
if($nome!=''){
$where[] = ' E.empr LIKE '."'%$nome%'".' ';
}
//Se seleccionou MORADA
if($morada!=''){
$where[] = ' E.morada LIKE '."'%$morada%'".' ';
}
//Se seleccionou CÓDIGO POSTAL
if($cp1!=''){
$where[] = ' E.cp1 LIKE '."'%$cp1%'".' ';
}
//Se seleccionou TELEFONE
if($telunique!=''){
$where[] = ' E.tel1 LIKE '."'%$telunique%'".' ';
}
//Se seleccionou FAX
if($faxunique!=''){
$where[] = ' E.fax1 LIKE '."'%$faxunique%'".' ';
}
//Se seleccionou E-MAIL
if($email!=''){
$where[] = ' E.email1 LIKE '."'%$email%'".' ';
}
//Se seleccionou DIRECTOR
if($director!=''){
$where[] = ' E.director LIKE '."'%$director%'".' ';
}
//Se seleccionou CHEFE DE RESERVAS
if($chefersv!=''){
$where[] = ' E.chefersv LIKE '."'%$chefersv%'".' ';
}
//Se seleccionou DESCRIÇÃO
if($descricao!=''){
$where[] = ' E.descricao LIKE '."'%$descricao%'".' ';
}
//Define os distrito
$where[] = ' D.ID=E.distrito_ID ';
// Se for diferente de "Qualquer" então coloca o "where"
if($f['distrito'] != 'Qualquer'){
$where[] = ' E.distrito_ID='.$f['distrito'];
}
//Se houver um concelho seleccionado
if($c[concelho] != 'Qualquer'){
$where[] = ' E.concelho_ID='.$c['concelho'].' ';
}
//Se forem Ilhas
if($f['distrito'] != '1' || $f['distrito'] != '13'){
} else {
$where[] = ' AND E.ilha_ID=IL.ID ';
}
//Se estiver definida a Ilha
if($f[ilha] != 'Qualquer'){
$where[] = ' E.ilha_ID='.$f['ilha'].' ';
}
// If "hits" is a valid number then add on a where clause
//if(isset($f['visual']) && strlen($f['hits_limit'])){
//$where[] = ' E.visual '.$f['visual'].' '.$f['hits_limit'];
//}
//Faz a junção dos "where's"
$query .= ' WHERE '.implode(' AND ',$where);
$query.=' ORDER BY E.empr ASC';
$sql=$query;
$result=mysql_query($sql) or die("SELECT: ".mysql_error());
$rows=mysql_num_rows($result);
//Definição de número de resultados na navegação
$lastr=(isset($lastr))?$lastr:10;
$firstr=(isset($firstr))?$firstr:0;
$num_pages=ceil($rows/$lastr);
// Decidir os limites definidos da pesquisa
//if(strlen($f['record_limit']) && strlen($f['record_start'])){
//$limit = ($f['record_limit'] - $f['record_start']);
//if($f['record_start'] >= 0 && $limit >= 0){
//$query .= ' LIMIT '.$f['record_start'].','.$limit;
//$firstr=$f['record_start'];
//$lastr=$limit;
$query.=' LIMIT '.$firstr.','.$lastr;
//}
//}
//Para troubleshooting poderemos apresentar o query completo. DESACTIVADO!
echo "$query<br>";
//////////////////////// START APRESENTAÇÃO DE RESULTADOS
//Este será o query completo para iniciar a pesquisa
$sql=$query;
$result=mysql_query($sql) or die("SELECT: ".mysql_error());
$rows2=mysql_num_rows($result);
$total=$rows;
//Ordenção de resultados
$byorder=(isset($byorder))?$byorder:"empreendimentos.cliente ASC, empreendimentos.empr";
$ordering=(isset($ordering))?$ordering:"ASC";
$reverse_ordering=($ordering=="ASC")?"DESC":"ASC";
$ordering_str=($ordering=="ASC")?"á":"â";
//Definição de número de resultados na navegação
$lastr=(isset($lastr))?$lastr:10;
$firstr=(isset($firstr))?$firstr:0;
$num_pages=ceil($rows/$lastr);
if(isset($jumptopage)){
if($jumptopage<=$num_pages){
$firstr=($jumptopage>0)?getRowFromPage($jumptopage):0;
} else {
$firstr=getRowFromPage($num_pages);
}
}
//Garante as ordenações ao navegar para as próximas páginas
$current_page=ceil($firstr/$lastr)+1;
$next_row=$firstr+$lastr;
$next_str=($next_row<$rows)?"<input onclick=\"window.location='".$PHP_SELF."?firstr=".$next_row."&lastr=".$lastr."&byorder=$byorder&ordering=$ordering&concelho_ID=".$concelho_ID."'\" type='button' name='button' value='VER PRÓXIMA' class='button2'>":" ";
//Garante as ordenações ao navegar para as próximas páginas
$previous_row=($firstr==0)?0:($firstr-$lastr);
$previous_str=($firstr!=0)?"<input onclick=\"window.location='".$PHP_SELF."?firstr=".$previous_row."&lastr=".$lastr."&byorder=$byorder&ordering=$ordering&concelho_ID=".$concelho_ID."'\"type='button' name='button' value='VER ANTERIOR' class='button2'>":" ";
//Remove action from querystring
$qstring=$QUERY_STRING;
//find 3 parameters;
$qstring=explode("&",$qstring);
$action_str=array_pop($qstring);
$empr_str=array_pop($qstring);
$ID_str=array_pop($qstring);
//rebuild rest of querystring (se for vazia é = "")
$qstring=implode($qstring,"&");
$qstring=($qstring!="")?"?".$qstring:"";
$ID=explode("=",$ID_str);
$ID=$ID[1];
?>
<form name='pesquisar' method='get' action='<?= $PHP_SELF ?>'>
<input type='hidden' name='lastr' value='<?= $lastr ?>'>
<input type='hidden' name='firstr' value='<?= $firstr ?>'>
<input type='hidden' name='qstring' value=<?= $qstring ?>'>
<a href="pesquisadistritos.php" class="bodyws_nav"><img border="0" src="images/setae.gif" width="11" height="11" alt="Clique"> Voltar à pesquisa<img border="0" src="images/spacer.gif" width="5" height="1"></a><a class="bodyw_nav">Visualizar
<select name='verresult' size='1' onchange="list=document.all.verresult; endRow=list.options[list.selectedIndex].value; window.location='<?= $PHP_SELF ?>?lastr='+endRow+'&firstr=0'" class="scrollboxes_main">
<option <?= ($lastr==10)?"selected":""; ?> value="10">10</option>
<option <?= ($lastr==25)?"selected":""; ?> value="25">25</option>
<option <?= ($lastr==50)?"selected":""; ?> value="50">50</option>
<option <?= ($lastr==100)?"selected":""; ?> value="100">100</option>
</select> resultados por página. <a class="bodyw_nav">Página <?= $current_page ?> de <?= $num_pages ?></a> <?= $previous_str ?> <?= $next_str ?><img border="0" src="images/spacer.gif" width="10" height="10" alt=""></a>
</form>
<?
//Apresenta o tempo demorado na pesquisa
$mtime = microtime();
$mtime = explode(" ",$mtime);
$mtime = $mtime[1] + $mtime[0];
$endtime = $mtime;
$totaltime =substr($endtime - $starttime,0,4);
//Definir a variável que será chamada no HTML para informar o TEMPO DE PESQUISA
echo "<br><font face='Verdana' size=2>Os resultados da sua pesquisa forma encontrados em <b>".$totaltime."</b> segundos</font><br>";
//Definir a variável que será chamada no HTML para informar O TOTAL DE EMPREENDIMENTOS ENCONTRADOS
echo "<br><font face='Verdana' size=2>Total de empreendimentos encontrados: <b>$total</b></font>";
$cnt=0;
while($fields=mysql_fetch_array($result)){
$id=$fields["id"];
$empr=$fields["empr"];
$visual=$fields["visual"];
//Guarda os emprs encontrados para o caso de diferente pesquisa
$emprarray[]=$id;
$cnt++;
?>
<!--### INICIAR AQUI O DISPLAY DE RESULTADOS ###--->
<!--//Display de resultados-->
<!--//echo "<br><font face='Verdana' size=2>Visualizações: <b>$visual</b> - <a href=\"../detalhe_empr.php?emprID=$id\" target=\"_blank\">$empr</a></font>";-->
<br><font face='Verdana' size=2>Nº <?= $cnt ?> - <a href="../detalhe_empr.php?emprID=<?= $id ?>" target="_blank"><?= $empr ?></a></font>
<!--### FINAL DO DISPLAY DE RESULTADOS ###--->
<? }
}
//Prepara os dados para envio pela URL para OUTRAS pesquisas
if(isset($emprarray)){
$empr=implode(",", $emprarray);
$serial=serialize($emprarray);
//Definir a variável que será chamada no HTML para o link de OUTRAS PESQUISAS
//echo "<br><br><a href='recebe_array.php?serial=$serial'>Clique aqui para pesquisar por características nos resultados encontrados</a>";
//echo "<br>$empr<br>";
foreach($emprarray as $value){
//echo "Este é o empreendimento nº $value<br>";
}
?>
<br><br><a href="<?= $PHP_SELF ?>?action=pesquisar">Voltar à pesquisa</a>
<br><a href='recebe_array.php?serial=<?= $serial ?>'>Clique aqui para pesquisar por características nos resultados encontrados</a>
<? } ?>