1

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?

2
  • Are you sure your query is correct and returns results? Commented Jan 27, 2010 at 3:33
  • Yeah, the first time I do the query the data are printed. Commented Jan 27, 2010 at 3:41

2 Answers 2

2

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.
}
Sign up to request clarification or add additional context in comments.

Comments

1

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

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.