开发者

Disappear the arrays generated with mysql_fetch_array() after use?

开发者 https://www.devze.com 2022-12-18 00:38 出处:网络
I have a typical database query: $query = mysql_query(\'SELECT titulo,referencia FROM cursos WHERE tipo=1 AND estado=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?


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.
}


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号