Re: Display all tables in database

From: Andy Hassall (andy_at_andyh.co.uk)
Date: 07/02/04


Date: Fri, 02 Jul 2004 20:31:10 +0100

On 2 Jul 2004 12:01:13 -0700, Laker64@hotmail.com (Telconstar99) wrote:

>> Your code differs significantly from the code on the suggested PHP website
>> page.
>>
>> Copy-and-paste the PHP.net code EXACTLY. Change the database names to
>> match your databases.
>
>The copy and pasted code works. You were absolutely correct. This
>puzzled me greatly. Because it looks to be the exact same code to me.
>I figured out what made a difference:
>
>This works:
>
> $result = mysql_list_tables("content");
>
> while ($row = mysql_fetch_row($result))
>{
> echo "Table: $row[0]\n";
>}
>
>This does not work however:
>
> while ($row = mysql_fetch_row(mysql_list_tables("content")))
>{
> echo "Table: $row[0]\n";
>}
>
>Notice the only difference is whether I stored
>mysql_list_tables("content") in a variable or not. Please somebody
>help me, that drives me crazy. Why does that make a single lick of
>difference? Thanks so much!

 A while ago:

>>> Because you re-execute mysql_list_tables() every time you loop.

 Consider the following, which is the same situation:

<pre>
<?php
function f1(&$x) {
    print "Fetched an entry.\n";
    return next($x);
}

function f2() {
    print "Generated new array.\n";
    return array(1,2,3,4);
}

$a = f2();
while ($x = f1($a)) {
    print "Value: $x\n";
}

print "Done.\n";

while ($x = f1(f2())) {
    print "Value: $x\n";
}

?>
</pre>

 The condition in a while() is executed every iteration.

 You seem to be expecting PHP to interpret:

> while ($row = mysql_fetch_row(mysql_list_tables("content")))

 As:

 First, execute mysql_list_tables("content") on the first iteration.
 Magically store that somewhere temporary.
 Then, on subsequent iterations, run mysql_fetch_row() on that temporary value,
but don't re-execute mysql_list_tables() again.
 Assign the result to $row and test for truth.

 Whereas the reality is it does exactly what you tell it; each time, it
evaluates the whole expression, which involves re-executing mysql_list_tables
and mysql_fetch_row and doing the assignment, meaning you end up with the first
row again (but from a different execution of mysql_list_tables() each time).

--
Andy Hassall <andy@andyh.co.uk> / Space: disk usage analysis tool
http://www.andyh.co.uk         / http://www.andyhsoftware.co.uk/space