Usamos cookies para medir audiência e melhorar sua experiência. Você pode aceitar ou recusar a qualquer momento. Veja sobre o iMasters.
queridos, não consigo coloar este código em minha página (paginação)
<?php
$pg = $_GET['pg'];
if(isset($pg)){
$pg = $pg;
}else{
$pg = 1;
}
$quantidade = 5;
$inicio = ($pg*$quantidade) - $quantidade;
$sql = mysql_query("SELECT * FROM tb_caes ORDER BY ANO_nasc_cao LIMIT $inicio, $quantidade");
while($linha = mysql_fetch_array($sql)){
$ano = $linha[' ANO_nasc_cao '];
echo "$ano<br>";
}
$sql_2 = mysql_query("SELECT * FROM tb_caes");
$total_registros = mysql_num_rows($sql_2);
$paginas = ceil($total_registros/$quantidade);
$links = 1;
echo "<a href='resultados.php?pg=1'>primeira página </a> ";
for($i = $pg-$links; $i <= $pg-1; $i++){
if($i<=0){
}else{
echo " <a href=' resultados.php?pg=".$i."'>".$i."</a> ";
}
}
echo "<a href=#>$pg</a>";
for($i = $pg+1; $i <= $pg+$links; $i++){
if($i>$paginas){
}else{
echo " <a href=' resultados.php?pg=".$i."'>".$i."</a> ";
}
}
echo " <a href=' resultados.php?pg=".$paginas."'>ultima página </a> ";
?>
// esse é meu código
<?php require_once('Connections/conexao.php'); ?>
<?php
// RESULTADO DO MEU RECORDSET
//MX Widgets3 include
require_once('includes/wdg/WDG.php');
if (!function_exists("GetSQLValueString")) {
function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "")
{
$theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;
$theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);
switch ($theType) {
case "text":
$theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
break;
case "long":
case "int":
$theValue = ($theValue != "") ? intval($theValue) : "NULL";
break;
case "double":
$theValue = ($theValue != "") ? "'" . doubleval($theValue) . "'" : "NULL";
break;
case "date":
$theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
break;
case "defined":
$theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
break;
}
return $theValue;
}
}
if (!function_exists("GetSQLValueString")) {
function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "")
{
$theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;
$theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);
switch ($theType) {
case "text":
$theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
break;
case "long":
case "int":
$theValue = ($theValue != "") ? intval($theValue) : "NULL";
break;
case "double":
$theValue = ($theValue != "") ? "'" . doubleval($theValue) . "'" : "NULL";
break;
case "date":
$theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
break;
case "defined":
$theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
break;
}
return $theValue;
}
}
$t_busca_r_gral = "-1";
if (isset($_GET['t_busca'])) {
$t_busca_r_gral = $_GET['t_busca'];
}
mysql_select_db($database_conexao, $conexao);
$query_r_gral = sprintf("SELECT * FROM tb_caes WHERE (raca_cao LIKE %s or nome_cao LIKE %s) and LIBERAR_ANUN_cao ='1' ORDER BY ANO_nasc_cao DESC", GetSQLValueString("%" . $t_busca_r_gral . "%", "text"),GetSQLValueString("%" . $t_busca_r_gral . "%", "text"));
$r_gral = mysql_query($query_r_gral, $conexao) or die(mysql_error());
$row_r_gral = mysql_fetch_assoc($r_gral);
$totalRows_r_gral = mysql_num_rows($r_gral);
?>
// tenho uma tabela onde exibe os dados
por favor me ajudem muito obrigada
BRUNA
como faço para ligar esta função ao meu código?
bejos
Bruna
Estava nos meus backups, minha classe de paginação xD:
paginator.class.php
<?php
/*
@ Class Paginator
@ Revision 03/10/2012
@ Powered by Erick-Master
@ Custom Tech Services
@ www.ctmts.com.br
*/
class paginator
{
public $total = 0;
public $result = 0;
public $current = 0;
public $maxPages = 0;
public $pointer = 0;
public $number = 0;
private $begin = 0;
private $end = 0;
private $pages = array();
public function start() $this->begin = ($this->current - 1) * $this->total;
$this->end = $this->begin + $this->total - 1;
$this->number = $this->result <= $this->total ? 1 : ceil($this->result / $this->total);
}
public function check() return $this->begin <= $this->pointer && $this->end >= $this->pointer ? TRUE : FALSE;
}
public function setPages() $count = $this->number;
for($i = 1; $i <= $count; $i++)
if($this->current <= $this->number)
if($i <= ($this->maxPages > 0 ? $this->maxPages : $count))
$this->pages[] = $i;
return array(count($this->pages), $this->pages);
}
public function finish() $this->total = 0;
$this->result = 0;
$this->current = 0;
$this->maxPages = 0;
$this->begin = 0;
$this->end = 0;
$this->pointer = 0;
$this->pages = array();
}
}
Exemplo de como usar:
<?php
header("Content-type: text/plain");
require("paginator.class.php");
$loop = array();
$loop[] = "a";
$loop[] = "b";
$loop[] = "c";
$loop[] = "d";
$loop[] = "e";
$loop[] = "f";
$loop[] = "g";
/*$loop[] = "h";
$loop[] = "i";
$loop[] = "k";
$loop[] = "l";
$loop[] = "m";
$loop[] = "n";*/
$paginator = new paginator();
$paginator->current = !empty($_GET['pag']) ? $_GET['pag'] : 1;
$paginator->maxPages = 5;
$paginator->result = count($loop);
$paginator->total = 2;
$paginator->start();
foreach($loop as $key => $value)
{
if($paginator->check())
printf("[%d] => %s\n", $key, $value);
$paginator->pointer++;
}
$pages = $paginator->setPages();
print "\n\n";
print $pages[0]."\n\n";
foreach($pages[1] as $key => $value)
{
printf("[%d]".($value == $paginator->current ? "#" : NULL).($key < $pages[0] - 1 ? " - " : NULL), $value);
}
Não comentei a classe porque na época eu programava apenas de forma privada (source codificada), ainda programo assim, mas alguns arquivos abertos eu comento, os privados não vejo necessidade...
Bom aproveito!
Erick-Master - Custom Tech Services
como incuir essa classe no meu código?
beijos
Bruna
>
como faço para ligar esta função ao meu código?
bejos
Bruna
é muito simples... é só você definir a constante URL_ROOT com o valor da URL raiz do site que você esta desenvolvendo.
e chamar essa função onde você quer se apareça a paginação...
a variavel $qs que a função necessita é a url adicional que fica depois do arquivo, por exemplo:
"arquivo.php" ai depois vem: ?varget1=valor&varget2=valor2
a URL completa iria ficar assim: arquivo.php?varget1=valor&varget2=valor2
ai você coloca desse jeito:
OBS: se não tiver url adicional, sete ela como: ""
exemplo:
echo Pagination("arquivo.php","varget1=valor&varget2=valor2",$totalDeRegistros,$porPagina,$varGetRef = 'pag',$links = 5,$botoesAdicionais = false)
$totalDeRegistros = Faça uma pesquisa no banco de dados e coloque aqui o total de registros que presisarão ser paginados
$porPagina = numero de itens que irá aparecer a cada pagina
o resto só modifique se você quiser msmo...
$varGetRef = a variavel que a função cria em GET que se refere a pagina atual
exemplo:
arquivo.php?varget1=valor&varget2=valor2&pag=1
$links = numero de links que aparece na paginação
$botoesAdicionais = se setado como true, aparece mais 2 botoes, que referem-se a PRIMEIRA PAGINA e a ULTIMA PAGINA
foi mau pela explicação meio ruim... mais espero que você tenha conseguido entender...^^
se você quiser, me adicionar no msn q eu te explico melhor...^^
jonataluizcioni@hotmail.com
<?php require_once('Connections/conexao.php'); ?>
<?php
// RESULTADO DO MEU RECORDSET
//MX Widgets3 include
require_once('includes/wdg/WDG.php');
if (!function_exists("GetSQLValueString")) {
function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "")
{
$theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;
$theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);
switch ($theType) {
case "text":
$theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
break;
case "long":
case "int":
$theValue = ($theValue != "") ? intval($theValue) : "NULL";
break;
case "double":
$theValue = ($theValue != "") ? "'" . doubleval($theValue) . "'" : "NULL";
break;
case "date":
$theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
break;
case "defined":
$theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
break;
}
return $theValue;
}
}
if (!function_exists("GetSQLValueString")) {
function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "")
{
$theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;
$theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);
switch ($theType) {
case "text":
$theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
break;
case "long":
case "int":
$theValue = ($theValue != "") ? intval($theValue) : "NULL";
break;
case "double":
$theValue = ($theValue != "") ? "'" . doubleval($theValue) . "'" : "NULL";
break;
case "date":
$theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
break;
case "defined":
$theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
break;
}
return $theValue;
}
}
$t_busca_r_gral = "-1";
if (isset($_GET['t_busca'])) {
$t_busca_r_gral = $_GET['t_busca'];
}
mysql_select_db($database_conexao, $conexao);
$query_r_gral = sprintf("SELECT * FROM tb_caes WHERE (raca_cao LIKE %s or nome_cao LIKE %s) and LIBERAR_ANUN_cao ='1' ORDER BY ANO_nasc_cao DESC", GetSQLValueString("%" . $t_busca_r_gral . "%", "text"),GetSQLValueString("%" . $t_busca_r_gral . "%", "text"));
$r_gral = mysql_query($query_r_gral, $conexao) or die(mysql_error());
$row_r_gral = mysql_fetch_assoc($r_gral);
$totalRows_r_gral = mysql_num_rows($r_gral);
?>
para adaptar essa função no código acima como faço
<table width="200' border ="1"
<tr>
<?php
//quero colocar o código da paginação aqui nessa tabela
?>
</td>
</tr>
</table>Bruna, seu código está desorganizado e complicado de entender.
Irei tentar te explicar como funciona a classe, veja bem, é bem simples:
Esse é o código inicial, ele vem após a sua query:
require("paginator.class.php");
$paginator = new paginator(); // -- Declara a classe
$paginator->current = !empty($_GET['pag']) ? $_GET['pag'] : 1; // -- Define a página atual através da GET "pag"
$paginator->maxPages = 5; // -- Número máximo de páginas
$paginator->result = count($loop); // -- Contagem dos valores do seu SELECT
$paginator->total = 2; // -- Total de valores por página
$paginator->start(); // -- Inicia o sistema
Para não ter que fazer 2 loops, você roda a query e não dê nenhum fetch e nem faz nenhum loop, faça desta forma:
// -- Exemplo de query
$query = mysql_select("SELECT * FROM tabela");
// -- Código inicial do paginator
$paginator = new paginator(); // -- Declara a classe
$paginator->current = !empty($_GET['pag']) ? $_GET['pag'] : 1; // -- Define a página atual através da GET "pag"
$paginator->maxPages = 5; // -- Número máximo de páginas
$paginator->result = mysql_num_rows($query); // -- Contagem dos valores do seu SELECT
$paginator->total = 7; // -- Total de valores por página
$paginator->start(); // -- Inicia o sistema
// -- Loop do MySQL
while($row = mysql_fetch_object($query))
{
/ If para ver se o valor está na página certa (Obrigatório) /
if($paginator->check())
{
/ seus scripts /
}
/ Linha obrigatória /
$paginator->pointer++;
}
Feito isso, o sistema já criou todas as páginas.
Agora vamos carrega-las, basta chamar a função "setPages", ela retorna todas as páginas em array:
$pages = $paginator->setPages();
// -- Esta função retorna o seguinte array: 0 => Quantidade de páginas, 1 => array das Páginas)
/ Loop das páginas, esta parte vai na sua tabela /
foreach($pages[1] as $key => $value)
{
if($value != $paginator->current) // -- Ver se a página é a atual
echo "Página ".$value." - ";
}
Abaixo, segue um exemplo para os botões "Anterior" e "Próxima":
/ Anterior: Esta parte vem antes do loop de pages /
if($paginator->current > 1)
{
$pagina = $paginator->current - 1;
echo "Anterior"; // -- O link seria ?pag=$pagina
}
/ Próxima: Esta parte vem após do loop de pages /
if($paginator->current < $pages[0])
{
$pagina = $paginator->current + 1;
echo "Próxima"; // -- O link seria ?pag=$pagina
}
Espero que tenha entendido, qualquer coisa poste sua dúvida.
Bom aproveito!
Erick-Master - Custom Tech Services
>
<?php require_once('Connections/conexao.php'); ?>
<?php
// RESULTADO DO MEU RECORDSET
//MX Widgets3 include
require_once('includes/wdg/WDG.php');
if (!function_exists("GetSQLValueString")) {
function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "")
{
$theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;
$theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);
switch ($theType) {
case "text":
$theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
break;
case "long":
case "int":
$theValue = ($theValue != "") ? intval($theValue) : "NULL";
break;
case "double":
$theValue = ($theValue != "") ? "'" . doubleval($theValue) . "'" : "NULL";
break;
case "date":
$theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
break;
case "defined":
$theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
break;
}
return $theValue;
}
}
if (!function_exists("GetSQLValueString")) {
function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "")
{
$theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;
$theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);
switch ($theType) {
case "text":
$theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
break;
case "long":
case "int":
$theValue = ($theValue != "") ? intval($theValue) : "NULL";
break;
case "double":
$theValue = ($theValue != "") ? "'" . doubleval($theValue) . "'" : "NULL";
break;
case "date":
$theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
break;
case "defined":
$theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
break;
}
return $theValue;
}
}
$t_busca_r_gral = "-1";
if (isset($_GET['t_busca'])) {
$t_busca_r_gral = $_GET['t_busca'];
}
mysql_select_db($database_conexao, $conexao);
$query_r_gral = sprintf("SELECT * FROM tb_caes WHERE (raca_cao LIKE %s or nome_cao LIKE %s) and LIBERAR_ANUN_cao ='1' ORDER BY ANO_nasc_cao DESC", GetSQLValueString("%" . $t_busca_r_gral . "%", "text"),GetSQLValueString("%" . $t_busca_r_gral . "%", "text"));
$r_gral = mysql_query($query_r_gral, $conexao) or die(mysql_error());
$row_r_gral = mysql_fetch_assoc($r_gral);
$totalRows_r_gral = mysql_num_rows($r_gral);
?>
para adaptar essa função no código acima como faço
<table width="200' border ="1"
<tr>
<?php
//quero colocar o código da paginação aqui nessa tabela
?>
</td>
</tr>
</table>
//quero colocar o código da paginação aqui nessa tabela
echo Pagination("arquivo.php","",$totalRows_r_gral,$porPagina=10,$varGetRef = 'pag',$links = 5,$botoesAdicionais = false)
//Mude o arquivo no primeiro parâmentro onde está "arquivo.php", coloque o nome do arquivo que está esta tabela, e se quiser, mude a quantidade de registros que aparece por pagina onde está "$porPagina=10", coloque a quantidade que quiser
ta dando esse erro, como resolver?
Warning: require(paginator.class.php) [function.require]: failed to open stream: No such file or directory in C:\wamp\www\site\resulgeral2.php on line 94
obrigada
Crie o arquivo "paginator.class.php" com o seguinte conteúdo:
<?php
/*
@ Class Paginator
@ Revision 03/10/2011
@ Powered by Erick-Master
@ Custom Tech Services
@ www.ctmts.com.br
*/
class paginator
{
public $total = 0;
public $result = 0;
public $current = 0;
public $maxPages = 0;
public $pointer = 0;
public $number = 0;
private $begin = 0;
private $end = 0;
private $pages = array();
public function start()
{
$this->begin = ($this->current - 1) * $this->total;
$this->end = $this->begin + $this->total - 1;
$this->number = $this->result <= $this->total ? 1 : ceil($this->result / $this->total);
}
public function check()
{
return $this->begin <= $this->pointer && $this->end >= $this->pointer ? TRUE : FALSE;
}
public function setPages()
{
$count = $this->number;
for($i = 1; $i <= $count; $i++)
if($this->current <= $this->number)
if($i <= ($this->maxPages > 0 ? $this->maxPages : $count))
$this->pages[] = $i;
return array(count($this->pages), $this->pages);
}
public function finish()
{
$this->total = 0;
$this->result = 0;
$this->current = 0;
$this->maxPages = 0;
$this->begin = 0;
$this->end = 0;
$this->pointer = 0;
$this->pages = array();
}
}resolvido pessoal, comprei a extensão de paginação
beijos
Bruna
Pô parece brincadeira, o companheiro Erick se esforçando para ajudar e de graça com sua class e a mina nem agradece, ainda por cima põe o link da compra no post.
Entendo pouquíssima coisa em PHP mas estou pesquisando muito e estudando através de tutoriais porque não tenho grana no momento pra fazer um curso, leio muitos foruns e tiro minhas dúvidas através deles, muitas vezes resolvidas mas aquelas dúvidas que não consigo resolver lendo eu pergunto, se alguém responder ótimo senão, tudo bem parto pra outra, e continuo estudando. Agora desistir fácil igual esta mina desistiu , nem pensar, como será que ela vai fazer quando precisar de algo e não puder comprar?
Erick, eu queria mesmo ter entendido de primeira como adicionar a sua classe no meu código, não entendí mas vou entender porque vou estudar isso aqui. Se eu precisar eu te pergunto, valeu parceiro.
Olá, bruna...
eu tenho uma função pronta para paginação de resultados...
é só você estiliza-la do seu jeito...
function Pagination($arquivoOUurl,$qs,$totalDeRegistros,$porPagina,$varGetRef = 'pag',$links = 5,$botoesAdicionais = false)
{