Limit items of a page with ARRAY

0

I've asked for help with a problem with php on a page, and actually it works fine until a request is made with an array, for example in the code below:

<div class="texto_busca"><b>RESULTADO DA BUSCA</b></div>
<?php
$expira_busca =1;
$tempo_on_busca= date('Y-m-d H:i:s');
$tempo_fim_busca= date('Y-m-d H:i:s',mktime(date('H'),date('i') -
$expira_busca,date('s'),date('m'),date('d'),date('Y')));
$negocio = strip_tags( $_POST['negocio'] );
$tipo_id   = $_POST['tipo'];
$cidade  = $_POST['cidade'];
$bairro = $_POST['bairro'] ;
$MySQLi->query("CREATE TABLE busca_bairros (
id INT(11) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
ip VARCHAR(255) NOT NULL,
negocio VARCHAR(255) NOT NULL,
tipo VARCHAR(255) NOT NULL,
cidade VARCHAR(255),
bairro VARCHAR(255),
date TIMESTAMP
) ");
$tipos=implode("|",$tipo_id);
$cidades=implode("|",$cidade);	
$bairros=implode("|",$bairro);	
$MySQLi->query("INSERT INTO busca_bairros(ip,negocio,tipo,cidade,bairro,date)VALUES('".$ip."','".$negocio."','".$tipos."','".$cidades."','".$bairros."','".$tempo_on_busca."')");
$MySQLi->query("DELETE FROM busca_bairros WHERE date<='".$tempo_fim_busca."'");
$MySQLi->query("ALTER TABLE busca_bairros AUTO_INCREMENT = 1;");

?>





<!-- AQUI É A DIV QUE RECEBE A REQUISIÇÃO DO JS -->

<div class="loading-div"><img src="img/status.gif" ></div>
<div id="results"><!-- content will be loaded here --></div>
</div>
<br /><br /><br /><br />
</div></div></div>

AND THE OTHER IS JS

<script async type="text/javascript">
$(document).ready( function (){
 //load initial records
$('#results').load('fetch_pages.php');
});
//executes code below when user click on pagination links
$("#results").on( "click", ".paginacao_ a", function (e){
e.preventDefault();
$(".loading-div").show(); //show loading element
var $form = $( this );
var page = $(this).attr("data-page"); //get page number from link
$("#results").load("fetch_pages.php",{"page":page}, function(){ //get content from PHP page
$(".loading-div").hide(); //once done, hide loading element
});   
});

</script>

And this code is where the search criteria is set:

if(isset($_POST) && isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest'){
include_once("config.php");$sessao_usuario_1=session_start();
$session_id=session_id();
$session=$_SESSION['UsuarioLogin'];
$senha=$_SESSION['UsuarioSenha'];
if (!isset($_SESSION)) session_start();
$nivel_necessario=NULL;   //include config file
//Get page number from Ajax POST
if(isset($_POST["page"])){
$page_number = filter_var($_POST["page"], FILTER_SANITIZE_NUMBER_INT, FILTER_FLAG_STRIP_HIGH); //filter number
if(!is_numeric($page_number)){die('Página inválida!');} //incase of invalid page number
}else{
$page_number = 1; //if there's no page number, set it to 1
}
$results = $MySQLi->query("SELECT id,ip,negocio,tipo,cidade,bairro FROM busca_bairros WHERE ip='".$ip."' ORDER BY id DESC");
$linha=mysqli_fetch_array($results);
$negocio_id=$linha['negocio'];
$tipo_id=$linha['tipo'];
$cidade_id=$linha['cidade'];
$bairro_id=$linha['bairro'];
$tipo_id_2=explode("|",$tipo_id);		
$cidade_id_2=explode("|",$cidade_id);
$bairro_id_2=explode("|",$bairro_id);

foreach ($tipo_id_2 as $key=> $tipo_id_3):
foreach ($cidade_id_2 as $key=> $cidade_id_3):
foreach ($bairro_id_2 as $kSey=> $bairro_id_3):
/* MONTA CRITERIOS DE BUSCA */              
$where = "i.ativo ='1'";
if(!empty( $negocio_id) ) {
$where .=" AND i.id_negocio_tipo=".$negocio_id."";
}if(!empty( $tipo_id_3 ) ) {
$where .=" AND i.id_tipo_imovel=".$tipo_id_3."";
}
if(!empty( $cidade_id_3 ) ) {
$where .=" AND i.id_cidade=".$cidade_id_3."";
}
if(!empty( $bairro_id_3 ) ) {
$where .=" AND i.bairro=".$bairro_id_3."";
}

echo $bairro_id_3 .",";
//get total number of records from database for pagination
$results = $MySQLi->query("SELECT i.*, t.tipo_nome, b.bairro, n.tipo, c.cidade FROM imoveis
i LEFT JOIN negocio_tipo n ON (n.id = i.id_negocio_tipo)
LEFT JOIN imoveis_tipo t ON (t.id = i.id_tipo_imovel)
LEFT JOIN cidades c ON (c.id = i.id_cidade)
LEFT JOIN bairros b ON (b.id = i.bairro)
WHERE ".$where."") or print(mysqli_error());
$get_total_rows =mysqli_num_rows($results);  //hold total records in variable
//break records into pages
$total_pages = ceil($get_total_rows / $item_per_page);
$pgs = ceil($total_pages  / $page_number);
$total_dados +=$get_total_rows;
//get starting position to fetch the records
$page_position = (($item_per_page*$page_number) - $item_per_page);
$pgst = ceil($total_dados / $item_per_page);
mysqli_free_result($results);
////////

endforeach;
endforeach;
endforeach;
if (!empty($total_dados)==1 ) {
echo "<br /><br /><div class='codigo_busca'><p>Foram encontrados <b>".$total_dados."</b> imóveis.</p>"."<br />";
echo "<p><span style='font-weight:bold; font-size:14px; color:#FF0;'><b>Página:</b></span> <span style='font-weight:bold; font-size:14px;'>".$page_number." de ".$pgst."</span></p></div><br /><br />";
}else{
echo"<br /><br /><br />";
echo "<div class='sem_busca'><b><span style='font: 22px Arial; color: #FFF; font-size: 15px;'><b>Nenhum imóvel encontrado! Tente uma nova busca !<br /><br /></b></span></b>";
echo"<br /><a href='javascript:window.history.go(-1)'><font color='#ffffff' size='2' face='Arial, Helvetica, sans-serif'><b>VOLTAR<br /><br /><img src='".$site."imagens/voltar.png'></b></font></a></div><br /><br />";
}}
$tipo_id_2=explode("|",$tipo_id);
$cidade_id_2=explode("|",$cidade_id);
$bairro_id_2=explode("|",$bairro_id);
foreach ($tipo_id_2 as $key=> $tipo_id_3):
foreach ($cidade_id_2 as $key=> $cidade_id_3):
foreach ($bairro_id_2 as $key=> $bairro_id_3):
/* MONTA CRITERIOS DE BUSCA */              
$where = "i.ativo ='1'";
if ( !empty( $negocio_id) ) {
$where .=" AND i.id_negocio_tipo=".$negocio_id."";
}if ( !empty( $tipo_id_3 ) ) {
$where .=" AND i.id_tipo_imovel=".$tipo_id_3."";
}
if ( !empty( $cidade_id_3 ) ) {
$where .=" AND i.id_cidade=".$cidade_id_3."";
}
if ( !empty( $bairro_id_3 ) ) {
$where .=" AND i.bairro=".$bairro_id_3."";
}
echo $total_dados;


$sql =$MySQLi->query("SELECT i.id, i.valor, i.foto_exibicao, i.quartos, i.garagem,i.mapa, i.codigo, t.tipo_nome, n.tipo AS negocio, c.cidade, c.uf, b.bairro FROM imoveis i
LEFT JOIN negocio_tipo n ON (n.id = i.id_negocio_tipo)
LEFT JOIN imoveis_tipo t ON (t.id = i.id_tipo_imovel)
LEFT JOIN cidades c ON (c.id = i.id_cidade)
LEFT JOIN bairros b ON (b.id = i.bairro)
WHERE ".$where." ORDER BY i.id  DESC LIMIT ".$page_position.", ".$item_per_page."") or print(mysqli_error());
while( $linha = mysqli_fetch_array( $sql ) ) {

$foto=$linha['foto_exibicao'];
$tipos=$linha['tipo_nome'];	
$tipo = $tipos;
$tipo  = strtolower( str_replace(" ", "-", strtr(utf8_decode(trim($tipo)), utf8_decode("áàãâéêíóôõúüñçÁÀÃÂÉÊÍÓÔÕÚÜÑÇ"),"aaaaeeiooouuncAAAAEEIOOOUUNC-")) );
$bairros=$linha['bairro'];	
$bairro = $bairros;
$bairro = strtolower( str_replace(" ", "-", strtr(utf8_decode(trim($bairro)), utf8_decode("áàãâéêíóôõúüñçÁÀÃÂÉÊÍÓÔÕÚÜÑÇ"),"aaaaeeiooouuncAAAAEEIOOOUUNC-")) );
$cidades=$linha['cidade'];	
$cidade = $cidades;
$cidade = strtolower( str_replace(" ", "-", strtr(utf8_decode(trim($cidade)), utf8_decode("áàãâéêíóôõúüñçÁÀÃÂÉÊÍÓÔÕÚÜÑÇ"),"aaaaeeiooouuncAAAAEEIOOOUUNC-")) );
$mapa=$linha['mapa'];
$id=$linha['id'];

?>
<div class="listaImoveis">
<?php
$img1='<a href="'.$site.'imovel/'.$tipo ."/".$bairro."/".$cidade."/".$linha['id'].'">
<img src="'.$site.'img_imoveis/'.$foto.'" width="170" height="130" alt="Imobiliária em São Paulo" /></a>
';
$img2='
<a href="'.$site.'imovel/'.$tipo ."/".$bairro."/".$cidade."/".$linha['id'].'">
<img src="'.$site.'img_imoveis/sem_foto.jpg" width="170" height="130" alt="Imobiliária em São Paulo" /></a>
';
if(!empty($foto)){
echo $img1;
}else{
echo $img2;
}


$url = getPage('https://maps.googleapis.com/maps/api/geocode/json?address='.$mapa.'&key=AIzaSyAQiIvxtURMaZKpE6Tj6hyJdfC72kgQI3g');
$output= json_decode($url);
$lat =  $output->results[0]->geometry->location->lat;
$long = $output->results[0]->geometry->location->lng;
if(!$mapa==1){
echo "<div class='alert_mapa'><img src='images/atencao.png'> Não foi possível abrir a localização pelo Google Mapas deste imóvel !</div>";
exit;
}else if($lat==$long){
echo "<div class='alert_mapa_2'><img src='images/atencao.png'> OPS Não existem coordenadas para este Endereço no google Mapas !</div>";

}

echo '<div class="pag_paginacao">';
echo paginate_function($item_per_page, $page_number, $get_total_row, $pgst);
echo '</div>';
################ pagination function #########################################
function paginate_function($item_per_page, $current_page, $total_records, $total_pages)
{
$pagination = '';
if($total_pages > 0 && $total_pages != 1 && $current_page <= $total_pages){ //verify total pages and current page number
$pagination .= '<ul class="paginacao_">';
$right_links    = $current_page + 1; 
$previous       = $current_page - 1; //previous link 
$next           = $current_page + 1; //next link
$first_link     = true; //boolean var to decide our first link
if($current_page > 1){
$previous_link = ($previous==0)? 1: $previous;
$pagination .= '<li class="last"><a href="#" data-page="1" title="Primeira Página"><img src="img/previous.png"></a></li>'; //first link
$pagination .= '<li class="last"><a href="#" data-page="'.$previous_link.'" title="Anterior"><img src="img/prev.png"></a></li>'; //previous link
for($i = ($current_page-2); $i < $current_page; $i++){ //Create left-hand side links
if($i > 0){
$pagination .= '<li class="last"><a href="#" data-page="'.$i.'" title="Page'.$i.'">'.$i.'</a></li>';
}
}   
$first_link = false; //set first link to false
}
if($first_link){ //if current active page is first link
$pagination .= '<li class="first">'.$current_page.'</li>';
}elseif($current_page == $total_pages){ //if it's the last active link
$pagination .= '<li class="first">'.$current_page.'</li>';
}else{ //regular current link
$pagination .= '<li class="first">'.$current_page.'</li>';
}
for($i = $current_page+1; $i < $right_links ; $i++){ //create right-hand side links
if($i<=$total_pages){
$pagination .= '<li class="first"><a href="#" data-page="'.$i.'" title="Page '.$i.'">'.$i.'</a></li>';
}
}
if($current_page < $total_pages){ 
$next_link = ($i > $total_pages) ? $total_pages : $i;
$pagination .= '<li class="last"><a href="#" data-page="'.$next_link.'" title="Próximo"><img src="img/next.png"></a></li>'; //next link
$pagination .= '<li class="last"><a href="#" data-page="'.$total_pages.'" title="Última Página"><img src="img/last.png"></a></li>'; //last link
}
$pagination .= '</ul>'; 
}
return $pagination; //return pagination links
}
?>
?>

This code is a page without refresh that I searched the net and adapted my needs, so it works fine when, for example, if you search by neighborhood (in this case an id) it does the pagination of good at the limit of 4, 5 or how many I want it to appear on each pagination, but when searching for more neighborhoods, there is set up the array, type id 13, 14, until then it looks good and brings the results, however instead appear only 4 per page, it brings 8 or more if each id has more than 1 property, summarizing, if in an id it finds 9 properties and in the other id it finds 10 it will throw everything on the same page because they are different ids instead to add the results and show only 4 per page and I can not find a solution and already tried to use it, but it did not roll, if someone has a solution, thank you ..

    
asked by anonymous 02.02.2018 / 22:52

0 answers