2012-08-25 25 views
11

Tengo una pregunta simple con respecto a PHP para comprobar si esta es la última fila de MySQL o no. Por ejemplo tengo este código:PHP Comprobar MySQL Última fila

$result = mysql_query("SELECT *SOMETHING* "); 

while($row = mysql_fetch_array($result)) 
{ 
if (*this is the last row*) 
{/* Do Something Here*/} 
else 
{/* Do Another Thing Here*/} 
} 

Tengo dificultades para comprobar si la fila es la última o no. ¿Alguna idea de cómo hacerlo? Gracias.

+1

Por favor, no use '' mysql_ * funciones para un código nuevo. Ya no se mantienen y la comunidad ha comenzado el [proceso de desaprobación] (http://goo.gl/KJveJ). Ver el [** cuadro rojo **] (http://php.net/manual/en/function.mysql-pconnect.php)? En su lugar, debe aprender sobre [declaraciones preparadas] (http://goo.gl/vn8zQ) y usar ya sea [PDO] (http://php.net/pdo) o [MySQLi] (http://php.net/ mysqli). Si no puede decidir, [este artículo] (http://goo.gl/3gqF9) le ayudará a elegir. Si le interesa aprender, [aquí hay un buen tutorial de PDO] (http://goo.gl/vFWnC). –

Respuesta

36

Puede utilizar mysql_num_rows() antes de su bucle while, y luego utilizar ese valor para su condición:

$numResults = mysql_num_rows($result); 
$counter = 0 
while ($row = mysql_fetch_array($result)) { 
    if (++$counter == $numResults) { 
     // last row 
    } else { 
     // not last row 
    } 
} 
8
$result = mysql_query("SELECT *SOMETHING* "); 

$i = 1; 
$allRows = mysql_num_rows($result); 
while($row = mysql_fetch_array($result)){ 

    if ($allRows == $i) { 
     /* Do Something Here*/ 
    } else { 
     /* Do Another Thing Here*/} 
    } 
    $i++; 
} 

pero por favor tome en consideración DOP

$db = new PDO('mysql:host=localhost;dbname=testdb', 'username', 'password'); 
$stmt = $db->query("SELECT * FROM table"); 
$allRows = $stmt->rowCount(); 
$i = 1; 
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) { 

    if ($allRows == $i) { 
     /* Do Something Here*/ 
    } else { 
     /* Do Another Thing Here*/} 
    } 
    $i++; 
} 
+1

+1 por mencionar PDO y publicar una solución PDO – Phil

0

Trate de tener un contador dentro del ciclo while y luego verificarlo contra mysql_num_rows()

2

Prueba esto:

$result = mysql_query("SELECT colum_name, COUNT(*) AS `count` FROM table"); 

$i = 0; 

while($row = mysql_fetch_assoc($result)) 
{ 
    $i++; 

    if($i == $row['count']) 
    { 
     echo 'last row'; 
    } 
    else 
    { 
     echo 'not last row'; 
    } 
} 
1
$allRows = $stmt->rowCount(); 

no funcionó para mí, tenían que usar:

$numResults = $result->num_rows; 
Cuestiones relacionadas