0
votes

Good eve everyone!

For some reason Database::fetchArray() is skipping the first $row of the query result set.

It prints all rows properly, only keeps missing out the first one for some reason, I assume there's something wrong with my fetchArray() function?

I ran the query in phpMyAdmin and it returned 4 rows, when I tried it on my localhost with the php file (code below) it only printed 3 rows, using the same 'WHERE tunes.riddim'-value ofcourse. Most similiar topics on google show that a common mistake is to use mysql_fetch_array() before the while(), which sets the pointer ahead and causes the missing of the first row, unfortunately I only have one mysql_fetch_array() call (the one within the while()-head).

<?php 

    $db->query("SELECT " .
                "riddims.riddim AS riddim, " .
                "riddims.image AS image, " .
                "riddims.genre AS genre, " .
                "tunes.label AS label, " .
                "tunes.artist AS artist, " .
                "tunes.tune AS tune, " .
                "tunes.year AS year," .
                "tunes.producer AS producer " .
                "FROM tunes " . 
                "INNER JOIN riddims ON tunes.riddim = riddims.riddim " .
                "WHERE tunes.riddim = '" . mysql_real_escape_string(String::plus2ws($_GET['riddim'])) . "'" .
                "ORDER BY tunes.year ASC");

    $ar = $db->fetchArray();

    for($i = 0; $i < count($ar) - 1; $i++)
    {
        echo $ar[$i]['riddim'] . " - " . $ar[$i]['artist'] . " - " . $ar[$i]['tune'] . " - " . $ar[$i]['label'] . " - " . $ar[$i]['year'] . "<br>";
    }

?>

Database::fetchArray() looks like:

public function fetchArray()
{

    $ar = array();

    while(($row = mysql_fetch_array($this->result)) != NULL)
        $ar[] = $row;

    return $ar;
}

Any suggestions appreciated!

3
Yes, you are not missing the first row, but the last row .. - dbf
You need to choose between for($i = 0; $i <= (count($ar) - 1); $i++) and for($i = 0; $i < count($ar); $i++) but do not shake them :-) - Alain Tiemblo

3 Answers

3
votes

You should remove -1 from the for loop

0
votes

The problem's in your while loop:

for($i = 0; $i < count($ar) - 1; $i++) 

if count ($ar) is 1, because there's one entry, your loop will never be called; try tweaking the check part:

for($i = 0; $i < count($ar) ; $i++) 
0
votes

You can also use a simple foreach:

foreach($db->fetchArray() as $row)
{
        echo $row['riddim'] # ...
}

It'll make your code more readable too.