Undefined variable error

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

Threaded View
I'm getting
PHP Notice: Undefined variable: db_list in C:\mypage.php on line xx

when I use the following code:

$conn = @mysql_connect( "localhost", "myname", "mypassword" )
    or die( "Sorry - could not connect to MySQL" );

$rs=     @mysql_list_dbs( $conn )
    or die( "Sorry - could not list databases" );

for( $row=0; $row < mysql_num_rows($rs); $row++ )
  $db_list .= mysql_tablename( $rs, $row ) . "<br>";  


This is copied straight out of a book I'm using to try to learn
about PHP and MySQL. Can someone tell me what's causing the
Undefined variable error? I didn't know that variables had to be

Using: PHP 5.0.1   MySQL 4.1.9

Re: Undefined variable error

Martin wrote:
Quoted text here. Click to load it

That's because you are concatenating the output from the function call with
$db_list without it's initialized.

Just initialize $db_list before you are using it and it'll work fine:

$db_list = '';
for ($row=0; $row < mysql_num_rows($rs); $row++) {
      $db_list .= mysql_tablename( $rs, $row ) . "<br>";

BTW, PHP will create variables on the fly, but throws notices when the error
reporting level is high enough. There are ways of suppressing these errors
without adjusting the error reporting level, but it's good programming
practice to define the variables you're going to use.


Re: Undefined variable error

You can also put the initialization right into the for loop, like this:

for ($row=0, $db_list = ''; $row < mysql_num_rows($rs); $row++) {
      $db_list .= mysql_tablename( $rs, $row ) . "<br
Quoted text here. Click to load it

Re: Undefined variable error

On Sun, 13 Feb 2005 22:24:25 +0100, "Janwillem Borleffs"

Quoted text here. Click to load it

One would think that the book's author should have known to do that.

Site Timeline