Reply to Re: How do I do this query?

Your name:

Reply:


Posted by Pedro Graca on 01/14/06 02:17

Rich wrote:
<snip>
> $sql = "SELECT DISTINCT name FROM grades order by name";
> $result = mysql_query($sql);

1 query

> if (!$result || mysql_num_rows($result) == 0) { echo mysql_error(); exit; }
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
nice construct!

> $grades = array();
> while ($row = mysql_fetch_row($result)) {
> $grades[$row[0]] = array();
> }
> mysql_free_result($result);
>
> foreach (array_keys($grades) as $name) {
> $sql = "SELECT class, grade FROM grades where name=\"$name\"";
> $result = mysql_query($sql);

a whole bunch of queries!!!
Don't do this if possible.
Avoid doing queries inside loops.

If your table has 1000 names you'd do 1001 queries (one for the
DISTINCT names and 1000 for the classes)

> if (!$result) { echo mysql_error(); exit; }
> while ($row = mysql_fetch_assoc($result)) {
> $grades[$name][$row['class']] = $row['grade'];
> }
> }
> mysql_free_result($result);

Why isn't this inside the foreach loop too?

> print_r($grades);
> ?>
>
> prints:
> Array (
> [jill] => Array ( [chem] => b [psych] => a )
> [joe] => Array ( [bio] => a )
> [john] => Array ( [psych] => b [chem] => a )
> )

Yes, it gets the desired results, but at a *very large* cost!

<snip>

--
Mail to my "From:" address is readable by all at http://www.dodgeit.com/
== ** ## !! ------------------------------------------------ !! ## ** ==
TEXT-ONLY mail to the whole "Reply-To:" address ("My Name" <my@address>)
may bypass my spam filter. If it does, I may reply from another address!

[Back to original message]


Удаленная работа для программистов  •  Как заработать на Google AdSense  •  England, UK  •  статьи на английском  •  PHP MySQL CMS Apache Oscommerce  •  Online Business Knowledge Base  •  DVD MP3 AVI MP4 players codecs conversion help
Home  •  Search  •  Site Map  •  Set as Homepage  •  Add to Favourites

Copyright © 2005-2006 Powered by Custom PHP Programming

Сайт изготовлен в Студии Валентина Петручека
изготовление и поддержка веб-сайтов, разработка программного обеспечения, поисковая оптимизация