user3109875
user3109875

Reputation: 828

What is the exact equivalent of mysqli_fetch_array function in PDO?

Since i've changed to PDO, i really can't seem to get the right function to use that would do exactly what mysqli_fetch_array() was doing, this happens probably because i don't realy understand the real diffrence between mysqli_fetch_array and PDO's fecth().

From some sources, while($row = mysqli_fetch_array($query) "fetches a single row from the resultset each time it is called.", whereas $row = $query->fetch() is returning the whole resultset in one single call.

I've asked two similar questions and one with a bounty but i can't seem to get a proper way around what i want to do.

, From this question,

$data = $query->fetchAll(PDO::FETCH_BOTH),

Using the first on this list just seems to behave differently from what mysqli_fetch_arrray does.

What i've tried returns so many errors in the while loop and crushes the browser at times, thanks to Chrome, i won't post that.

HERE's what i want to do.

$counter = 0;    
while($row = mysqli_fetch_array($query)){
   $counter++;
    echo $counter;
    echo $row['Name'];
}

If we have three rows: RESULT;

1
TRIQUESHA

2
STACEY

3
DAQUEN

NOW PDO

$count = 0;
while($row = $query->fetch(PDO::FETCH_BOTH)){
$counter++;
    echo $counter;
    echo $row['Name'];
}

Again if we have three rows: PDO RESULT;

3
TRIQUESHA

3
STACEY

3
DAQUEN

It's not counting, its returning the total number of rows instead, if i had 50 rows, it would repeat 50 on each row.

What am I doing wrong?

Upvotes: 1

Views: 10217

Answers (1)

Hanky Panky
Hanky Panky

Reputation: 46900

$count and $counter are different variables. – hjpotter92

That's a typo when i was reproducing the code here. – user3109875

That very typo is the real problem here. You are seeing 3 in PDO version being repeated cause its your $counter variable set to 3 after your mysqli loop, and it never gets updated. You need to reset it correctly before the PDO loop to see.

//$count = 0;   // Wrong
$counter=0;    //  Correct. 
while($row = $query->fetch(PDO::FETCH_BOTH)){
    $counter++; 
    echo $counter;
    echo $row['Name'];
}

Edit:

While Mark M correctly pointed out what I overlooked, I still believe that is the cause of this error. See this revision in that question's edit history

$count = 0;
while($row = $query->fetch(PDO::FETCH_BOTH)){
$count++;
    echo $counter;    //This will always remain 3 because you are incrementing $count
    echo $row['Name'];
}

This will exactly cause the behavior that this answer suggests. Now if that is the actual code then that's the actual reason, if that's different from what it really is, then this answer is invalid.

Upvotes: 4

Related Questions