Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have been doing MYSQL just fine for a while now but am trying to learn how to do all that i know with PDO; what I am struggling with now is a simple SQL select, and then I loop through all the rows and dump the corresponding column values into a variable; and then I can do something with the variables for that row while in the loop; here is the way I used to do it with mysql:

$result42 = mysql_query("SELECT * FROM members");

while($row = mysql_fetch_array($result42, MYSQL_BOTH))
{
$user_id=$row['user_id'];
$user_name=$row['user_name'];
$email=$row['email'];

// do something with info for each user; like maybe echo their info...
}

I am attempting to do the same thing with PDO but not finding anything quite like what I am trying to do…

I found some code which uses fetchall and fetchassoc and seems to be putting it in an array; but I have no idea how to loop through the array and get each value on the row like i did with mysql above; and I am not even sure if the PDO that i have here can do that…

this is what I have:

$stmt = $dbh->prepare("SELECT * FROM members");

$products = array();
if ($stmt->execute()) {
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    $products[] = $row;
}
}

All i want to do is end up cycling through each row getting the values, doing something with them and then moving on to the next row…

Can anyone help with this? Thanks...

share|improve this question
1  
You can do the same thing in your pdo code sample. Just change the $products[] = $row; to your $user_id=$row['user_id']; $user_name=$row['user_name']; $email=$row['email']; // do something with info for each user; like maybe echo their info... –  Sean Sep 20 '14 at 4:28
1  
while under the loop, just do what you have to do, what seems to be stopping you from doing that? –  Ghost Sep 20 '14 at 4:33
1  
thanks Sean, that worked great; and Ghost, I guess I am still learning the ropes on this and so I just did not know that what I had would work so easily; but I thank you both so much for your help... –  gman_donster Sep 20 '14 at 4:41
    
@gman_donster actually those codes on both mysql and pdo while code blocks is just similar, $row contains the info per row. in the PDO while block, just use $row accordingly to what you need to do, anyway, if it worked just fine then good for you –  Ghost Sep 20 '14 at 4:50

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.