views:

79

answers:

2

I have a typical database query:

$query = mysql_query('SELECT titulo,referencia FROM cursos WHERE tipo=1 AND estado=1');

and I can convert it in an array and print the data:

while ($results=mysql_fetch_array($query)): ?>
echo $results['referencia'];
// and so...
endwhile;

but in some cases I need to print the same data in another part of the web page, but the $results array seems to be empty (I use var_dump($results) and I get bool(false)). I plan to use what I learned reading Create PHP array from MySQL column, but not supposed to mysql_fetch_array() creates an array? So, what happen?

+1  A: 

Try this

while($results = mysql_fetch_array($query))
{
    $data[] = $results;
}

Now, all of your results are in $data, and you can do whatever you want from there.


As Anthony said, you might want to make sure that data is actually being retrieved from the query. Check if any results are being returned by echo mysql_num_rows($query). That should give you the number of rows you got

Chacha102
Thanks Chacha102, that's the method I supposed to be used and I'll try it, but I still wonder why the arrays generated by `mysql_fetch_array()` seem to disappear.
Tae
+1  A: 

Tae, the reason that your $result is false at the end of the while loop is that mysql_fetch_array returns false when it reaches the end of the query set. (See the PHP Docs on the subject) When you reach the end of the query set $results is set to false and the while loop is exited. If you want to save the arrays (database row results) for later, then do as Chacha102 suggests and store each row as it is pulled from the database.

$data = array();
while($results = mysql_fetch_array($query)) {
    $data[] = $results;
}
foreach ($data as $result_row) {
    echo $result_row['referencia'];
    ... etc.
}
Sean Vieira