p2p.wrox.com Forums

Need to download code?

View our list of code downloads.


  Return to Index  

beginning_php thread: problem displaying multiple variables via echo


Message #1 by gregbd@s... on Mon, 27 May 2002 18:55:30
I am a total newbie to php. I have a script that works displaying 
multiple database enteries in a different table in MySQL. When I 
change the table references etc. It will only disply one entry from the 
new table. There are actually five entries.... but it only displays one 
record...

The script that works is...

$authors = @mysql_query("SELECT id, authorname FROM 
authors");
if (!$authors) {
  echo("<p>Error retrieving authors from database!<br />".
       "Error: " . mysql_error() . "</p>");
  exit();
}

while ($author = mysql_fetch_array($authors)) {
  $id   = $author["id"];
  $authorname = htmlspecialchars($author["authorname"]);
  echo("<li>$authorname ".
       "[<a href='editauthor.php?id=$id'>Edit</a> | ".
       "<a href='deleteauthor.php?id=$id'>Delete</a>]</li>");
}

The script that only calls one database entry is...

$main_projects = @mysql_query("SELECT id, projectname, 
description FROM main_projects");
if (!$main_projects) {
  echo("<p>Error retrieving authors from database!<br />".
       "Error: " . mysql_error() . "</p>");
  exit();
}

while ($main_projects = mysql_fetch_array($main_projects)) {
  $id   = $main_projects["id"];
  $projectname = htmlspecialchars($main_projects["projectname"]);
  $description = htmlspecialchars($main_projects["description"]);
  
  echo("<li><b>$projectname:</b> ". "$description ".
       "<br>[<a href='edit_main_projects.php?id=$id'>Edit</a> | ".
       "<a href='delete_main_projects.php?id=$id'>Delete</a>]</li>");
}

Any help would be appreciated. :o)
Message #2 by "Tonsil" <tonsil@s...> on Tue, 28 May 2002 01:01:02 -0400
It's because of this line:

while ($main_projects = mysql_fetch_array($main_projects)) {

You're reassigning the value of $main_projects and the next time 
through the loop it ganks, because it's trying to fetch the array of an 
invalid statement.

Try somthing like this, it will all be okay:

$main_projects = @mysql_query("SELECT id, projectname, 
description FROM main_projects");
if (!$main_projects) {
  echo("<p>Error retrieving authors from database!<br />".
       "Error: " . mysql_error() . "</p>");
  exit();
}

while ($skippy = mysql_fetch_array($main_projects)) {
  $id   = $skippy["id"];
  $projectname = htmlspecialchars($skippy["projectname"]);
  $description = htmlspecialchars($skippy["description"]);
  
  echo("<li><b>$projectname:</b> ". "$description ".
       "<br>[<a href='edit_main_projects.php?id=$id'>Edit</a> | ".
       "<a href='delete_main_projects.php?id=$id'>Delete</a>]</li>");
}

Cheers!


On 27 May 02, at 18:55, gregbd@s... wrote:

> I am a total newbie to php. I have a script that works displaying 
> multiple database enteries in a different table in MySQL. When I 
> change the table references etc. It will only disply one entry from the 
> new table. There are actually five entries.... but it only displays one 
> record...
> 
> The script that works is...
> 
> $authors = @mysql_query("SELECT id, authorname FROM 
> authors");
> if (!$authors) {
>   echo("<p>Error retrieving authors from database!<br />".
>        "Error: " . mysql_error() . "</p>");
>   exit();
> }
> 
> while ($author = mysql_fetch_array($authors)) {
>   $id   = $author["id"];
>   $authorname = htmlspecialchars($author["authorname"]);
>   echo("<li>$authorname ".
>        "[<a href='editauthor.php?id=$id'>Edit</a> | ".
>        "<a href='deleteauthor.php?id=$id'>Delete</a>]</li>");
> }
> 
> The script that only calls one database entry is...
> 
> $main_projects = @mysql_query("SELECT id, projectname, 
> description FROM main_projects");
> if (!$main_projects) {
>   echo("<p>Error retrieving authors from database!<br />".
>        "Error: " . mysql_error() . "</p>");
>   exit();
> }
> 
> while ($main_projects = mysql_fetch_array($main_projects)) {
>   $id   = $main_projects["id"];
>   $projectname = htmlspecialchars($main_projects["projectname"]);
>   $description = htmlspecialchars($main_projects["description"]);
>   
>   echo("<li><b>$projectname:</b> ". "$description ".
>        "<br>[<a href='edit_main_projects.php?id=$id'>Edit</a> | ".
>        "<a href='delete_main_projects.php?id=$id'>Delete</a>]</li>");
> }
> 
> Any help would be appreciated. :o)
> 



_________________________________________________
This email has been brought to you by:
     House Arrest Daycare (tm)
"Hey, I figgered I wasn't goin' nowhere nohow..."
Message #3 by gregbd@s... on Tue, 28 May 2002 21:18:44
Thanks! That worked great... I am not sure I really understand the 
difference though. Also, the secind variable $description will not  
echo. 

$main_projects = @mysql_query("SELECT id, projectname, 
description FROM main_projects");
if (!$main_projects) {
  echo("<p>Error retrieving authors from database!<br />".
       "Error: " . mysql_error() . "</p>");
  exit();
}

while ($projectname = mysql_fetch_array($main_projects)) {
  $id   = $projectname["id"];
  $projectname = htmlspecialchars($projectname["projectname"]);
  $description = htmlspecialchars($description["description"]);
  
  echo("<li><b>$projectname:</b> $description ".
       "<br>[<a href='edit_main_projects.php?id=$id'>Edit</a> | ".
       "<a href='delete_main_projects.php?id=$id'>Delete</a>]</li>");
}

Any ideas?

Message #4 by "Tonsil" <tonsil@s...> on Tue, 28 May 2002 16:31:04 -0400
Well, the reason yours wasn't working before was that you need two 
separate variables, $main_projects and $projectname. 

When you had
while ($main_projects = mysql_fetch_array($main_projects)) {
you were returning an array that you fetched from a sql query, which 
was specified by $main_projects, and storing that array into 
$main_projects, which meant that it no longer contained the sql query. 
The next time you looped, it would call mysql_fetch_array() with the 
stored array from the first time, which won't work. 

Your new problem.. change the line:
$description = htmlspecialchars($description["description"]);
to
$description = htmlspecialchars($projectname["description"]);
and it should work fine.

I'll buy the first round, how's that? :D

On 28 May 02, at 21:18, gregbd@s... wrote:

> Thanks! That worked great... I am not sure I really understand the 
> difference though. Also, the secind variable $description will not  
> echo. 
> 
> $main_projects = @mysql_query("SELECT id, projectname, 
> description FROM main_projects");
> if (!$main_projects) {
>   echo("<p>Error retrieving authors from database!<br />".
>        "Error: " . mysql_error() . "</p>");
>   exit();
> }
> 
> while ($projectname = mysql_fetch_array($main_projects)) {
>   $id   = $projectname["id"];
>   $projectname = htmlspecialchars($projectname["projectname"]);
>   $description = htmlspecialchars($description["description"]);
>   
>   echo("<li><b>$projectname:</b> $description ".
>        "<br>[<a href='edit_main_projects.php?id=$id'>Edit</a> | ".
>        "<a href='delete_main_projects.php?id=$id'>Delete</a>]</li>");
> }
> 
> Any ideas?
> 
> 



_________________________________________________
This email has been brought to you by:
     House Arrest Daycare (tm)
"Hey, I figgered I wasn't goin' nowhere nohow..."
Message #5 by gregbd@s... on Thu, 30 May 2002 01:34:07
Thanks for your help and explanation. Your suggestion for the new 
code did fiix the other problem that some of the other entries would 
not display. However, now the description tag does not display the 
contents of the field $description (results below).. 

Web Page templates: W 
[Edit | Delete]
*	Greg's New Category: G 
[Edit | Delete]
*	Logo Development: L 
[Edit | Delete]
*	test2: t 
[Edit | Delete]
*	stacy: s 
[Edit | Delete]

I tried changing a the variables - but I am stumped again!  :(  The data 
following the ":" is supposed to be the contents of the $description 
field but for some reason it is picking up what appears to be the first 
letter of the $projectname field which you sugegsted I reference as:

>Your new problem.. change the line:
$description = htmlspecialchars($description["description"]);
to
$description = htmlspecialchars($projectname["description"]);
and it should work fine.

I really appreciate your help but do not want to abuse your kindness 
and support.

As I have been thinking about this issue - it seems to me that the 
issue must relate to the array/loop - for some reason it cannot call 
the results from $description. Am I on the right track?  

It strikes me that there are probably more than one way to call these 
variables from the database. Once again, any help, suggestions or 
direction would be greatly appreciated...

Thanks in advance!
Message #6 by "Nikolai Devereaux" <yomama@U...> on Wed, 29 May 2002 18:00:06 -0700
Okay, maybe I can help out.

Unfortunately, Tonsil's solution was flawed with the same problem that he
was trying to solve -- You're overwriting a variable and then trying to use
the original value.

Let's go through your code line by line.  It appears that this isn't as much
a PHP problem as a *programming* problem.  Draw pictures and diagrams if it
helps understand what's going on.

Here goes.

<line 1>
$main_projects = @mysql_query("SELECT id, projectname,
                     description FROM main_projects");
</line>

Okay, $main_projects is now a RESULT RESOURCE IDENTIFIER.  PHP uses this as
an internal link to the result set from your query.

<line 2>
if (!$main_projects) {
  echo("<p>Error retrieving authors from database!<br />".
       "Error: " . mysql_error() . "</p>");
  exit();
}
</line>

Nothing to talk about here, except that $main_projects will be false if the
query failed.  All valid result resource identifiers evaluate to true in a
conditional expression.

<line 3>
while ($projectname = mysql_fetch_array($main_projects)) {
</line>

This is probably a bad name for your variable.  $projectname is not a name
at all, it's an array containing the id, projectname, and description fields
of a single row of your query results.

For example, let's say your database looked like this:

id   projectname            description
1    Web Page Templates     Templates for a web page.  Duh.
2    Logo Development       Development of logos.  Duh.

The first call to mysql_fetch_array will return you an array with the
following fields:

(I'll list the contents in this format: [index] => value)

   [0]           =>  1
   [id]          =>  1
   [1]           =>  Web Page Templates
   [projectname] =>  Web Page Templates
   [2]           =>  Templates for a web page.  Duh.
   [description] =>  Templates for a web page.  Duh.


<line 4>
  $id   = $projectname["id"];
</line>

This looks correct because you're using $projectname as an array.  In our
example, $id is now set to 1.

<line 5>
  $projectname = htmlspecialchars($projectname["projectname"]);
</line>

Uh oh, you messed up here. =)  $projectname is OVERWRITTEN with the value
"Web Page Templates".  It is no longer an array.  The assignment operator
(=) evaluates the right hand side of the equation and assigns that value to
the variable specified on the left.  Since the right hand side is evaluated
first, $projectname is still an array when you access the "projectname"
index of that array.  After this line is done, $projectname = "Web Page
Templates" and the rest of your results are lost.

<line 6>
  $description = htmlspecialchars($projectname["description"]);
</line>

Okay, remember how in the last line you changed $projectname from an array
to a string?  You're trying to access the string as an array, which doesn't
work -- not really.  Strings allow you to use numerical array index notation
to get a particular character out of a string.

For example:

$str = "Hello";
echo $str[1];  // outputs an 'e'.

But notice something -- you're not passing an INTEGER to the array index,
even though PHP requires one.  So PHP automatically converts the string
"description" into an integer, 0.

How does it do this?  Simply put, PHP creates integers from strings by
parsing the string character by character.  Each digit encountered is
appended to the number.  As soon as a non-digit character is encountered,
the parsing stops.

Examples:

"99 bottles of beer on the wall" evaluates to 99.
"24 25 26" evaluates to 24.
"description" evaluates to 0.

Let's plug this new knowledge back into your line:

  $description = htmlspecialchars($projectname[0]);

$projectname[0] is the first character of $projectname.  Since $projectname
was "Web Page Templates", $description is now set to "W".


<line 7>
  echo("<li><b>$projectname:</b> $description ".
       "<br>[<a href='edit_main_projects.php?id=$id'>Edit</a> | ".
       "<a href='delete_main_projects.php?id=$id'>Delete</a>]</li>");
</line>

Let's recap what our variables are set to:

$main_projects   is a MySQL result resource link
$id              is 1
$projectname     is "Web Page Templates"
$description     is "W"

Therefore, the output you're seeing is correct.


I think you'd have a much easier time if you used better variable names.  By
reading your code, one gets the impression that you don't quite understand
what it is you're trying to do -- you're in the stage where you program your
site by writing a bunch of code that doesn't make much sense, and then
trying to solve the warning and error messages.  It gets the job done, but
it takes a long time, and PHP being a scripting language, you don't get as
many errors and warnings as you do a whole boatload of buggy output that's
hard to track down.


Let me suggest this rewriting:

$query = "SELECT id, projectname, description "
       . "FROM main_projects";

$result = mysql_query($query);

if (!$result)
{
  exit("<p>Error retrieving project info from database!<br />".
       "Error: " . mysql_error() . "</p>");
}

while ($project_data = mysql_fetch_array($result))
{
  $id   = $project_data["id"];
  $name = htmlspecialchars($project_data["projectname"]);
  $desc = htmlspecialchars($project_data["description"]);

  echo("<li><b>$name:</b> $desc <br>".
       "[<a href='edit_main_projects.php?id=$id'>Edit</a> | ".
       "<a href='delete_main_projects.php?id=$id'>Delete</a>]</li>");
}




Hope this helps,

Nik

Message #7 by "Tonsil" <tonsil@s...> on Thu, 30 May 2002 02:40:55 -0400
Come again?!? Did you read my replies? I corrected him - twice.


On 29 May 02, at 18:00, Nikolai Devereaux wrote:

> Okay, maybe I can help out.
> 
> Unfortunately, Tonsil's solution was flawed with the same problem that
> he
> was trying to solve -- You're overwriting a variable and then trying to
> use
> the original value.



_________________________________________________
This email has been brought to you by:
     House Arrest Daycare (tm)
"Hey, I figgered I wasn't goin' nowhere nohow..."
Message #8 by gregbd@s... on Thu, 30 May 2002 14:02:58
Nik: thanks loads. Your solution worked nicely. 

>I think you'd have a much easier time if you used better variable 
names.  

The variable names make sense to me. What would better variable 
names look like to you?

>By reading your code, one gets the impression that you don't quite >
>understand what it is you're trying to do -- you're in the stage where 
>you program your site by writing a bunch of code that doesn't make 
>much sense, and then trying to solve the warning and error 
messages.  

Ouch, but true.

>It gets the job done, but it takes a long time, and PHP being a 
scripting language, you don't get as many errors and warnings as 
you do a whole boatload of buggy output that's hard to track down.

I would agree...

Your assessment that i do not quite understand what it is I am trying 
to do is correct. I will have to slow down and take the time to read and 
follow Beginning PHP4 to gain an understanding of what I am trying 
to do rather than trying short cut and debug.

Thanks for the constructive critique and honesty.
Message #9 by gregbd@s... on Thu, 30 May 2002 14:06:58
> Come again?!? Did you read my replies? I corrected him - twice.

Tonsil: I appreciate your help. However, I did not knbow what I did not 
know. I am guilty of trying to short cut rather than taking the time to 
learn PHP from the ground up and do the job right from the get go.

Thanks for your contribution - I did learn something from your 
contribution and I appreciated the support. 

:o)
Message #10 by "Tonsil" <tonsil@s...> on Thu, 30 May 2002 11:54:33 -0400
Hey, no sweat... that line was directed solely at Nik for suggesting I 
was leading people astray when I in fact wasn't.

 I know how aggravating it can be to try to do something for the first 
time, only to get hung up on one minor detail. Good luck to ya!!!

On 30 May 02, at 14:06, gregbd@s... wrote:

> > Come again?!? Did you read my replies? I corrected him - twice.
> 
> Tonsil: I appreciate your help. However, I did not knbow what I did not 
> know. I am guilty of trying to short cut rather than taking the time to 
> learn PHP from the ground up and do the job right from the get go.
> 
> Thanks for your contribution - I did learn something from your 
> contribution and I appreciated the support. 
> 
> :o)
> 


Message #11 by "Nikolai Devereaux" <yomama@u...> on Thu, 30 May 2002 09:25:52 -0700
> Come again?!? Did you read my replies? I corrected him - twice.

Now I'm being nit picky, but your replies were:

<quote #1>
You're reassigning the value of $main_projects and the next time
through the loop it ganks, because it's trying to fetch the array of an
invalid statement.
</quote>

This fixed the problem with $main_projects being overwritten and therefore
losing its original (but needed) value.


<quote #2>
Your new problem.. change the line:
$description = htmlspecialchars($description["description"]);
to
$description = htmlspecialchars($projectname["description"]);
and it should work fine.
</quote>

This fixed that he was using $description instead of the $projectname array,
but ignored the problem you fixed in quote 1 that he was overwriting
$projectname on the line immediately before this one.


Take care,

Nik

Message #12 by "Nikolai Devereaux" <yomama@u...> on Thu, 30 May 2002 09:34:10 -0700
> >I think you'd have a much easier time if you used better variable
> names.
>
> The variable names make sense to me. What would better variable
> names look like to you?

The snippets that I provided named the variables according to what they
actually are.  I was referring to the fact that $projectname was not, in
fact, the project name, but rather the project info array containing the id,
name, and description.  Stuff like that.


> Thanks for the constructive critique and honesty.

I hope you don't think I was harping on you.  I wouldn't offer such a
lengthy and detailed response to your problem if I wasn't concerned with
having you learn WHY things work or don't work.  The fact that you're
writing scripts as you learn will be the greatest helping factor in you
learning the language.  Reading through the books is all fine and dandy, but
don't do it to the exclusion of working real-world practices.

Also, remember that PHP books are tools for learning basic concepts.  I've
read through lots of code from PHP books and disagreed with almost all of it
on a real-world working site level.  That said, I would encourage you to
remain subscribed to this list (and pro_php, too) because the solutions
posted here are generally in response to specific problems, and are
generally a bit more thought out than a toy script for a book example.


Take care,

Nik

Message #13 by gregbd@s... on Thu, 30 May 2002 20:34:04
Nik: 

No I never felt harped on - I really appreciated your lengthy response 
and support. It was just sort of embarassing to be so much a newbie 
-- I knew I was missing something -- now I know what and why and it 
has armed me with a strategy. Thanks again!

>I hope you don't think I was harping on you.  I wouldn't offer such a
lengthy and detailed response to your problem if I wasn't concerned 
with having you learn WHY things work or don't work.  The fact that 
you're writing scripts as you learn will be the greatest helping factor in 
you learning the language.  Reading through the books is all fine and 
dandy, but don't do it to the exclusion of working real-world practices.

Also, remember that PHP books are tools for learning basic 
concepts.  I'veread through lots of code from PHP books and 
disagreed with almost all of it on a real-world working site level.  That 
said, I would encourage you to remain subscribed to this list (and 
pro_php, too) because the solutions posted here are generally in 
response to specific problems, and aregenerally a bit more thought 
out than a toy script for a book example.

Message #14 by "Nikolai Devereaux" <yomama@u...> on Thu, 30 May 2002 12:45:54 -0700
> No I never felt harped on - I really appreciated your lengthy response
> and support. It was just sort of embarassing to be so much a newbie
> -- I knew I was missing something -- now I know what and why and it
> has armed me with a strategy. Thanks again!

Don't be embarassed!  This is a place to come to learn about the language,
so newbies are expected and welcomed.

There have been people on these lists that continue to ask the same
questions over and over again (with slight differences based on application
context).  Those are the people who are NOT learning the language, but
continue to get stuck with a problem and ask (in some cases demand) someone
here to solve it for them.

That's the kind of behavior that I'd be embarassed about.

You learned a little bit more about programming in general -- about keeping
track of variables, and how to diagram or draw out these things as a "pencil
and paper debugger".

A "variable" is defined by FOUR things:
   name
   data type
   value
   scope

The name gives you, the programmer, an access point to the variable.

The data type of the variable defines the range of possible values that
variable can hold, which operations can be performed on it, and in some
cases gives you the size in memory that the variable will consume.

The value is the data stored in the variable, which is ultimately what we as
programmers are interested in.

The scope of the variable tells us where in the program it's valid to access
the variable.

If I ever put up that website I've been talking about, an expanded version
of this would make a decent article.


Take care,

Nik


  Return to Index