Jump to content


Photo

Paginação


  • Faça o login para participar
4 replies to this topic

#1 INFOSOFT

INFOSOFT

    Turista

  • Usuários
  • 47 posts
  • Sexo:Masculino
  • Localidade:Belo Horizonte

Posted 16/08/2011, 14:52

Oi pessoal... novamente eu to "num mato sem coelho".
Preciso fazer uma paginação de uma pagina de busca, eu já tentei um milhão de código, mas não está dando certo.
Se alguém puder me ajudar...
O código que resulta a busca é o seguinte:

--------- buscado.php ---------
<?php
include ("includes/conexao.php");

$search = $_POST['search'];
if (empty($search)){
echo "Voce nao preencheu os campos da busca";
}
else{
global $search;
$sql=mysql_query("SELECT * FROM servicos WHERE busca LIKE '%$search%' AND publicar='1' ORDER BY valor DESC");
$linhas=@mysql_num_rows($sql);
}
$linhas=@mysql_num_rows($sql);
if ($linhas==0){
echo "<br><br><br><br><br><br><br><br><br><br><br><br><center><font face='arial' color='#8CAC0B' style='font-size: 14pt'>Não existe nada com o argumento pesquisado!</center>
<script language='javascript'>alert('Não existe nada com o argumento pesquisado!');history.go(-1);</script>";
}

?>

<?
if ($linhas >=1){
while ($coluna = mysql_fetch_array($sql)){
$id = $coluna["id"];
$publicar = $coluna["publicar"];
$valor = $coluna["valor"];
$prazo = $coluna["prazo"];
$login = $coluna["login"];
$titulo = $coluna["titulo"];
$servico = $coluna["servico"];
$cidade = $coluna["cidade"];
$coduser = $coluna["coduser"];
$limit=35;
$titulo = substr($titulo, 0,$limit);
?>
----------------------------------------
Até que eu tenho outras páginas com paginação, mas PARA ADERIR A ESTA AQUI TÁ MUITO COMPLICADO.
Nada que eu tentei deu certo! Se alguém puder me dar um help...
MUITO OBRIGADO!

#2 Diego Bezerra

Diego Bezerra

    Diego Bezerra

  • Moderadores
  • 938 posts
  • Sexo:Masculino
  • Localidade:Amazonas
  • Interesses:Iniciando no C# com MSSQL.

Posted 16/08/2011, 17:30

Ola tenho esta classe e funciona legallll

<?php
class PS_Pagination {
	var $php_self;
	var $rows_per_pagina = 10; //Number of records to display per pagina
	var $total_rows = 0; //Total number of rows returned by the query
	var $links_per_pagina = 5; //Number of links to display per pagina
	var $append = ""; //Paremeters to append to pagination links
	var $sql = "";
	var $debug = false;
	var $conn = false;
	var $pagina = 1;
	var $max_paginas = 0;
	var $offset = 0;
	

	function PS_Pagination($connection, $sql, $rows_per_pagina = 10, $links_per_pagina = 5, $append = "") {
		$this->conn = $connection;
		$this->sql = $sql;
		$this->rows_per_pagina = (int)$rows_per_pagina;
		if (intval($links_per_pagina ) > 0) {
			$this->links_per_pagina = (int)$links_per_pagina;
		} else {
			$this->links_per_pagina = 5;
		}
		$this->append = $append;
		$this->php_self = htmlspecialchars($_SERVER['PHP_SELF'] );
		if (isset($_GET['pagina'] )) {
			$this->pagina = intval($_GET['pagina'] );
		}
	}
	

	function paginate() {
		//Check for valid mysql connection
		if (! $this->conn || ! is_resource($this->conn )) {
			if ($this->debug)
				echo "MySQL connection missing<br />";
			return false;
		}
		
		//Find total number of rows
		$all_rs = @mysql_query($this->sql );
		if (! $all_rs) {
			if ($this->debug)
				echo "SQL query failed. Check your query.<br /><br />Error Returned: " . mysql_error();
			return false;
		}
		$this->total_rows = mysql_num_rows($all_rs );
		@mysql_close($all_rs );
		
		//Return FALSE if no rows found
		if ($this->total_rows == 0) {
			if ($this->debug)
				echo "A Consulta Não Retornou Nada.";
			return FALSE;
		}
		
		//Max number of paginas
		$this->max_paginas = ceil($this->total_rows / $this->rows_per_pagina );
		if ($this->links_per_pagina > $this->max_paginas) {
			$this->links_per_pagina = $this->max_paginas;
		}
		
		//Check the pagina value just in case someone is trying to input an aribitrary value
		if ($this->pagina > $this->max_paginas || $this->pagina <= 0) {
			$this->pagina = 1;
		}
		
		//Calculate Offset
		$this->offset = $this->rows_per_pagina * ($this->pagina - 1);
		
		//Fetch the required result set
		$rs = @mysql_query($this->sql . " LIMIT {$this->offset}, {$this->rows_per_pagina}" );
		if (! $rs) {
			if ($this->debug)
				echo "A paginação falhou. Verifique sua consulta.<br /><br />Erro Retornado: " . mysql_error();
			return false;
		}
		return $rs;
	}
	

	function renderFirst($tag = 'P&aacute;gina anterior') {
		if ($this->total_rows == 0)
			return FALSE;
		
		if ($this->pagina == 1) {
			return "$tag ";
		} else {
			return '<a href="'. $_SERVER['PHP_SELF']. '?pagina=1' . $this->append . '">' . $tag . '</a> ';
		}
	}
	
	/**
	 * Display the link to the last pagina
	 *
	 * @access public
	 * @param string $tag Text string to be displayed as the link. Defaults to 'Last'
	 * @return string
	 */
	function renderLast($tag = 'Pr&oacute;xima p&aacute;gina') {
		if ($this->total_rows == 0)
			return FALSE;
		
		if ($this->pagina == $this->max_paginas) {
			return $tag;
		} else {
			return ' <a href="'. $_SERVER['PHP_SELF'].'?pagina=' . $this->max_paginas . $this->append . '">' . $tag . '</a>';
		}
	}
	
	/**
	 * Display the next link
	 *
	 * @access public
	 * @param string $tag Text string to be displayed as the link. Defaults to '>>'
	 * @return string
	 */
	function renderNext($tag = '&gt;&gt;') {
		if ($this->total_rows == 0)
			return FALSE;
		
		if ($this->pagina < $this->max_paginas) {
			return '<a href="'. $_SERVER['PHP_SELF'].'?pagina=' . ($this->pagina + 1) . $this->append . '">' . $tag . '</a>';
		} else {
			return $tag;
		}
	}
	
	/**
	 * Display the previous link
	 *
	 * @access public
	 * @param string $tag Text string to be displayed as the link. Defaults to '<<'
	 * @return string
	 */
	function renderPrev($tag = '&lt;&lt;') {
		if ($this->total_rows == 0)
			return FALSE;
		
		if ($this->pagina > 1) {
			return ' <a href="' . $_SERVER['PHP_SELF']. '?pagina=' . ($this->pagina - 1) . '&' . $this->append . '">' . $tag . '</a>';
		} else {
			return " $tag";
		}
	}
	
	/**
	 * Display the pagina links
	 *
	 * @access public
	 * @return string
	 */
	function renderNav($prefix = '<span class="pagina_link">', $suffix = '</span>') {
		if ($this->total_rows == 0)
			return FALSE;
		
		$batch = ceil($this->pagina / $this->links_per_pagina );
		$end = $batch * $this->links_per_pagina;
		if ($end == $this->pagina) {
			//$end = $end + $this->links_per_pagina - 1;
		//$end = $end + ceil($this->links_per_pagina/2);
		}
		if ($end > $this->max_paginas) {
			$end = $this->max_paginas;
		}
		$start = $end - $this->links_per_pagina + 1;
		$links = '';
		
		for($i = $start; $i <= $end; $i ++) {
			if ($i == $this->pagina) {
				$links .= $prefix . " $i " . $suffix;
			} else {
				$links .= ' ' . $prefix . '<a href="' . $_SERVER['PHP_SELF']. '?pagina=' . $i .  $this->append . '">' . $i . '</a>' . $suffix . ' ';
			}
		}
		
		return $links;
	}
	
	/**
	 * Display full pagination navigation
	 *
	 * @access public
	 * @return string
	 */
	function renderFullNav() {
		return $this->renderFirst() . '&nbsp;' . $this->renderPrev() . '&nbsp;' . $this->renderNav() . '&nbsp;' . $this->renderNext() . '&nbsp;' . $this->renderLast();
	}
	
	/**
	 * Set debug mode
	 *
	 * @access public
	 * @param bool $debug Set to TRUE to enable debug messages
	 * @return void
	 */
	function setDebug($debug) {
		$this->debug = $debug;
	}
}
?>

exemplo de como usar ela

<table width="100%" border="0" cellspacing="1" cellpadding="1">
    <tr style="background-image:url(img/button.png)">
      <th width="50%" style="background-image:url(img/button.png)">Nome</th>
      <th width="8%" style="background-image:url(img/button.png)">Imagem</th>
      <th width="8%" style="background-image:url(img/button.png)">Status</th>
      <th width="20%" style="background-image:url(img/button.png)">&nbsp;</th>
    </tr>
<?php 
	$sql = 'SELECT * FROM noticias ORDER BY idnot DESC';
	//Create a PS_Pagination object
	$pager = new PS_Pagination($con, $sql, 10, 3);
	//The paginate() function returns a mysql
	//result set for the current page
	$rs = $pager->paginate();
	//Loop through the result set
	while($row = mysql_fetch_assoc($rs)) {
		$idnot = $row['idnot'];
		$titulo = $row['titulo'];
		$imagem = $row['imagem'];
		$status = $row['status'];
		$categoria = $row['categoria'];


?>
      <tr>
      <td style="border-bottom:2px solid #333"><?php echo $titulo ?></td>
      <td style="border-bottom:2px solid #333"><a href="artigo.php?<?php echo $url_get.'=atimagem&idnot='.$idnot?>"><?php echo "<img src=\"../upload/$imagem\" width=\"85\" style=\"border:2px solid #CCC\">" ?></a></td>
      
      <?php 
      if($status == 1 ){?>
	<td style="border-bottom:2px solid #333"><a href="artigo.php?<?php echo $url_get.'=desativar&idnot='.$idnot.'&status='.$status?>"><img src="img/online.gif" width="80" height="30"></a></td>
    <?php
	  }else{
		  ?>
	<td style="border-bottom:2px solid #333"><a href="artigo.php?<?php echo $url_get.'=desativar&idnot='.$idnot.'&status='.$status?>"><img src="img/offline.gif" width="80" height="30"></a></td>
	<?php
	  }
			  
	   ?>
      <td style="border-bottom:2px solid #333"><a href="artigo.php?a=deletar&idnot=<?php echo $idnot ?>"><img src="img/menu_del.gif" width="100" height="30" /></a>
      <a href="artigo.php?<?php echo $url_get.'=editar&idnot='.$idnot.'&categoria='.$categoria ?>"><img src="img/menu_ed.gif" width="100" height="30" /></a></td>
    </tr><?php
	}
	//Display the navigation
	echo $pager->renderFullNav();
	 ?>
  </table>

Att.
Diego Bezerra
Agência Kernel - em Breve
Email/msn: diegobezerra@outlook.com
Facebook

#3 INFOSOFT

INFOSOFT

    Turista

  • Usuários
  • 47 posts
  • Sexo:Masculino
  • Localidade:Belo Horizonte

Posted 25/08/2011, 22:52

Obrigado, mas não funfou não!

O problema maior é que na busca tem:
---
$search = $_POST['search'];
if (empty($search)){
echo "Voce nao preencheu os campos da busca";
}
else{
global $search;
$sql=mysql_query("SELECT * FROM servicos WHERE busca LIKE '%$search%' AND publicar='1' ORDER BY valor DESC");
$linhas=@mysql_num_rows($sql);
}
$linhas=@mysql_num_rows($sql);
if ($linhas==0){
---
Sem isso não tem busca e sem busca não tem dados!
O que tá f... é que o script para paginação depente deste código inicial!
Mas msm assim valeu!

#4 André Manoel

André Manoel

    Doutor

  • Usuários
  • 996 posts
  • Sexo:Masculino
  • Localidade:Brasilia

Posted 26/08/2011, 09:34

Vc pode colocar todas as coisas na tela .... e utilizar esse plugin de javascript que é lindo!!!

http://www.datatables.net/
Iniciando na Ajuda On line...

Posted Image Meu post lhe ajudou? Reputar/votar é uma das formas de agradecer.

#5 INFOSOFT

INFOSOFT

    Turista

  • Usuários
  • 47 posts
  • Sexo:Masculino
  • Localidade:Belo Horizonte

Posted 31/08/2011, 20:44

Vc pode colocar todas as coisas na tela .... e utilizar esse plugin de javascript que é lindo!!!
http://www.datatables.net/

-------------
Dá não andré, tem que colocar tudo na tela, mas isso não é possível, pq é uma busca!
-------------

FIZ ASSIM...
-----------------------------------------------------
BUSCA DADOS:

<?php
include ("includes/conexao.php");

$search = $_POST['search'];
if (empty($search)){
echo "Voce nao preencheu os campos da busca";
}
else{
global $search;

$total_reg = "5"; // número de registros por página
if (!$pagina) {
$pc = "1";
} else {
$pc = $pagina;
}
$inicio = $pc - 1;
$inicial = $inicio * $total_reg;

$limite = mysql_query("SELECT * FROM servicos LIMIT $inicial, $total_reg");
$busca = mysql_query("SELECT * FROM servicos WHERE busca OR titulo LIKE '%$search%' AND publicar='1' ORDER BY valor DESC");
$linhas=@mysql_num_rows($busca);
}
$linhas=@mysql_num_rows($busca);
if ($linhas==0){
echo "<br><br><br><br><br><br><br><br><br><br><br><br><center><font face='arial' color='#8CAC0B' style='font-size: 14pt'>
Nenhum resultado foi encontrado para a palavra $search!
<br><font face='arial' color='#000000' style='font-size: 10pt'>Redirecionando...
</center>
<script language='javascript'>alert('Nenhum resultado foi encontrado para a palavra $search!');history.go(-1);</script>";
}

$todos = mysql_query("$busca");
$tr = mysql_num_rows($todos); // verifica o número total de registros
$tp = $tr / $total_reg; // verifica o número total de páginas

$total_reg = mysql_num_rows($busca);

if ($linhas >=1){
while ($coluna = mysql_fetch_array($limite)){
$id = $coluna["id"];
$publicar = $coluna["publicar"];
$valor = $coluna["valor"];
$prazo = $coluna["prazo"];
$login = $coluna["login"];
$titulo = $coluna["titulo"];
$servico = $coluna["servico"];
$cidade = $coluna["cidade"];
$coduser = $coluna["coduser"];
$limit=47;
$titulo = substr($titulo, 0,$limit);
?>

PAGINAÇÃO:

<?
// agora vamos criar os botões "Anterior e próximo"
$intervalo = 5;
$anterior = $pc -1;
$proximo = $pc +1;
$flag1 = floor($pc/$intervalo);
$pi = ($flag1 * $intervalo );
$pf = $pi + $intervalo;

echo "<div id='nave' align='center'>";

if ($pc > 1) {
echo "<a href='?pagina=$anterior' class='categoria' target='_self'><font face='Arial' style='font-size: 9pt'>« Anterior</a> ";
}else{
echo "<font face='Arial' style='font-size: 9pt' style='color: #FFFFFF'>« Anterior&nbsp;</font>";
}
if ($pc > 1) {
echo "<font class='preto'>|</font>";
}else{
echo "";
}

for ($pi; $pi < $pf; $pi++) {
// Se número da página for menor que total de páginas
if ($pi <= $tp) {
if ($pc == $pi) {
// se página atual for igual a página selecionada
if ($pi > "0") {
echo "<font face='Arial' style='font-size: 9pt'><b class='preto'>" . $pi . "</b>&nbsp;";
}
} else {
// se for diferente, aparece o link para a página
if ($pi > "0") {
echo "<a href='?pagina=" . $pi . "' class='preto' target='_self'><font face='Arial' style='font-size: 9pt'>" . $pi . "</a>&nbsp;";
}

}
}
}
if ($pc < $tp) {
echo "<font class='preto'>|</font>";
}else{
echo "";
}
if ($pc < $tp) {
echo "&nbsp;<a href='?pagina=$proximo' class='categoria' target='_self'><font face='Arial' style='font-size: 9pt'>Próxima »</a>";
}else{
echo "&nbsp;<font class='categoria' style='color: #FFFFFF'><font face='Arial' style='font-size: 9pt'>Próxima »</font>";
}
echo "</div>";
// e para finalizar, fechamos a conexão com servidor MySQL
mysql_close($conn);
?>
-------------------------------------------

O PROBLEMA AGORA É QUE:
FAÇO UMA BUSCA E MOSTRA "Encontrado(s) 7 resultado(s) da pesquisa por teste"
ENCONTRA 7, LISTANDO 5 ITENS E NÃO APARECE NADA NO FINAL DA PÁGINA (SOMENTE O ANTERIOR E PRÓXIMO invisíveis)
FUSEI DEMAIS, E ATÉ CONSIGO QUE APAREÇA: "Anterior [1] Próximo", MAS NÃO VAI PARA PÁGINA NENHUM E ABRE UMA
PÁGINA QUE NÃO EXISTE!
------------------------------------------
Alguém pode ajudar?
Desde já agradeço!




1 user(s) are reading this topic

0 membro(s), 1 visitante(s) e 0 membros anônimo(s)

IPB Skin By Virteq