Ir para conteúdo

Arquivado

Este tópico foi arquivado e está fechado para novas respostas.

Bootstrap

Ler o próximo registro em uma query MySQL no PHP

Recommended Posts

Oi, pessoal,

 

Eu tenho esse código em PHP

$sql = "Select * from..."
$result = mysql_query($sql,$connection);
while ($row = mysql_fetch_array($result)) {
......
}

 

O que eu estou precisando é conseguir ler o próximo registro dentro do laço para fazer a comparação com o registro atual. Por exemplo:

while ($row = mysql_fetch_array($result)) {
......
if (ID DO PRÓXIMO RECORD != ID DO ATUAL RECORD) {
faça-alguma-coisa
}
}

 

O resultado que estou buscando é algo como:

 

Produto 1
Produto 1
<quebra de linha ou qualquer outra ação>
Produto 2
Produto 2
Produto 2
Produto 2
<quebra de linha ou qualquer outra ação>

 

Eu cheguei bem próximo da solução usando o código abaixo que encontrei na net, o único problema é que o último registro da query é sempre ignorado (não entra no while):

$current_row=mysql_fetch_array($result); //read $current_row
while ($next_row = mysql_fetch_array($result)) { //read $next_row
......
if ($current_row['id']!=$next_row['id']) { //compare it
.....
.....
}
$current_row=$next_row; //$next_row become current_row on next step 
}

 

travei forte nesse problema e agradeço qualquer ajuda.

Compartilhar este post


Link para o post
Compartilhar em outros sites

Dessa forma que você está fazendo, não vai dar certo, tente assim:

<?php

while ( $fetch = mysql_fetch_array ( $result ) ) {
	$all [ ] = $fetch ;
}

$i = 1 ;
while ( $data = mysql_fetch_array ( $result ) ) {
	$next = $all [ $i ] ;

	if ( $data [ 'id' ] != $next [ 'id' ] ) {
		// ...
	}
	++ $i ;		
}

 

É mesma coisa que você fazer isto :

<?php
for ( $i = 0 ; $i < 15 ; ++ $i ) {
	$all [ ] = $i ;
}

foreach ( $all as $k => $v ) {

	$next = ( $k + 1 ) ;
	if ( isset ( $all [ $next ] ) ) {
		// tem próximo 
		// próximo : atual
		echo $all [ $next ] , ': ' , $v , PHP_EOL ;
	}		

}

Compartilhar este post


Link para o post
Compartilhar em outros sites

Olá, Andrey

 

Muito obrigado pela atenção e ajuda.

 

Infelizmente, eu não consegui implementar a sua solução para o meu problema (não consegui entender a lógica).

Andei pesquisando e encontrei que a solução provavelmente envolve o uso do operador isset... algo como:

 

if (isset($proximo) && $proximo != $atual){  //compare it

 

Mas também não consegui avançar muito com essa parte.

 

Será que o caminho pode ser esse?

Compartilhar este post


Link para o post
Compartilhar em outros sites

Certo, primeiro você aplica um fetch, coloca todos os registros em um ARRAY:

<?php

       while ( $fetch = mysql_fetch_array ( $result ) ) {
               $all [ ] = $fetch ;
       }

 

Depois, você pode ou não fazer outro fetch, só que estaria utilizando um contador, que nesse caso, serve para pegar a linha no array $all, com esse contador ( sabendo que o array é incrementado sucessivamente 1 , 2 , 3 , 4 , 5 ) , iniciamos em 1 , pois quando um array é populado da forma que eu fiz, começa em 0 , só que, se eu começar em 1, o que vai acontecer, na hora de iterar, o loop estaria em ( 0 , 1 , 2 , 3 , 4 , 5 ) , e o contador em ( 1 , 2 , 3 , 4 , 5 , 6 ) , daí só verificar com o isset, se existe esse índice setado, que no caso é o próximo ..

 

Para evitar de fazer outro fetch, você pode simplesmente fazer desta forma:

<?php

       while ( $fetch = mysql_fetch_array ( $result ) ) {
               $all [ ] = $fetch ;
       }

if ( is_array ( $all ) ) {
	foreach ( $all as $i => $data ) {
		$next = ( $i + 1 ) ; 
		if ( isset ( $all [ $next ] ) ) {
			// tem próximo
			$_next = $all [ $next ] ;
			if ( $_next [ 'id' ] != $data [ 'id' ] ) {
				// diferente
			} else {
				// igual
			}
		} // não tem próximo
	}
}

 

dá uma olhada no exemplo em prática :seta: http://ideone.com/Ozm4p ..

<?php

       $all = array ( ) ;
array_push ( $all , 1 , 2 , 3 , 4 , 5 , 6 ) ;  

// pra cada item em $all, será atribuido $i ( índice ) = $v ( valor ) 
foreach ( $all as $i => $v ) {
	echo 'Current: ' , $v , PHP_EOL ; 
	$_i = ( $i + 1 ) ; // próximo índice
	if ( isset ( $all [ $_i ] ) ) { // tem próximo
		$next = $all [ $_i ] ; 
		echo 'Next: ' , $next , PHP_EOL ;
	}

}

Compartilhar este post


Link para o post
Compartilhar em outros sites

Oi, pessoal,

 

O usuário mikosiko do forum http://forums.devnetwork.net me passou o código que resolve perfeitamente o problema. Estou postando aqui para caso algum dia alguém precise.

// Example
 $heading_column = '<whatever is the name of your heading column>';
 $last_heading = null;

 while($row = your_fetch_assoc_statement){
	// detect a change in the heading value and output the new heading
	if($last_heading != $row[$heading_column]){
			// detect if it is not the first heading - close out the previous section
			if($last_heading != null){
					// your code to close the previous section (table, div, etc)...
					echo "close section<br />";
			}
			// output the new heading here...
			echo "new section title - {$row[$heading_column]}<br />";

			// save the new heading as the last_heading
			$last_heading = $row[$heading_column];
	}
	// output the actual data here...
	echo "data - {$row['your_data']}<br />";
 }
 // if there was any output - close out the last section
 if($last_heading != null){
	// your code to close the previous section (table, div, etc)...
	echo "close section<br ?>";
 }

Compartilhar este post


Link para o post
Compartilhar em outros sites

×

Informação importante

Ao usar o fórum, você concorda com nossos Termos e condições.