Jump to content

Need some help... mysql_fetch_assoc :(


Barchie

Recommended Posts

Hey Guys,

 

This might be simple, im not sure... Im having mysql_fetch_assoc (and array for that matter) only returning one row :S

 

The code is as follows:

 

$query = "SELECT * FROM departments WHERE 1";
    $result = mysql_query($query);

    $num_rows = mysql_num_rows($result);
    $result = mysql_fetch_assoc($result);

 

Weird part is $num_rows is returning 2 rows.  But mysql_fetch_assoc array only has one entry.

 

I dont get it :( I have another query further down, exactly the same format that returns the right amount of data.

 

Any ideas? Im lost.

 

 

Link to comment
https://forums.phpfreaks.com/topic/202963-need-some-help-mysql_fetch_assoc/
Share on other sites

To get all the rows, you need to use a loop:

<?php
$query = "SELECT * FROM departments";
$result = mysql_query($query);
$num_rows = mysql_num_rows($result);
while ($result = mysql_fetch_assoc($result)) {
//
//  do stuff here
//
}
?>

 

Ken

Thanks for you response, unfortunately it is still only returning one result.

 

I originally tried:

 

$query = "SELECT * FROM departments WHERE 1";
$result = mysql_query($query);
$results = mysql_fetch_assoc($result);

foreach($results as $result){
echo $result['id'].'<br/>';
}

 

But after realising that i was only getting one id, i started to cut the code back.  I added a row to the db and num_rows is returning 3 rows now, but mysql_fetch_assoc is still only returning on result.

 

Ensured query is rigt, ran it in php my admin and received 3 results as expected.

   

 

No, you need to loop through the results, not the one row:

<?php
$query = "SELECT * FROM departments";
$result = mysql_query($query);
$num_rows = mysql_num_rows($result);
while ($results = mysql_fetch_assoc($result)) {
   echo $results['id'] . '<br>';
}
?>

 

Ken

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.