Re: WHERE problem

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



On Mon, February 19, 2007 2:32 pm, Bruce Cowin wrote:
>>>> Mike Shanley <thebarmy@xxxxxxxxxxxxxxxxx> 20/02/2007 9:23:08 a.m.
>>>> >>>
> I'd like to think I understood code a little better than this, but
> I've
> got a problem with my WHERE...
>
> I know it's the WHERE because I get a good result when I leave it out.
> And the random function is also working... I honestly can't figure it
> out. Thanks in advance for help with this laughable prob.
> ---------------------------
> // How many are there?
>
> $result = mysql_query("SELECT count(*) FROM fortunes");
> $max = mysql_result($result, 0);
>
> // Get randomized!... the moderated way...
>
> $randi = mt_rand(1, $max-1);
> $q = "SELECT text FROM fortunes WHERE index = '$randi'";
> $choose = mysql_query($q);
> $chosen1 = mysql_fetch_array($choose);

Are you certain that your 'index' field runs from 1 to $max-1 and you
will never DELETE a fortune leaving a hole in your 'index' values?...

Unless you really really really need the quality of the Merseinne
Twister random generator, you could just do:
SELECT text FROM fortunes ORDER BY rand() LIMIT 1
(Or is it random() in MySQL?  I always confuse mysql/pg random
function name...)

Also, 'text' is a field type in SQL, so you may need:
SELECT `text` to make it not be reserved word.
Ditto for index -> `index` perhaps.

> // Ready to ship...
>
> $fortune = '<span class="quotecyc">&quot;' . $chosen1[0] .
> '&quot;<br/>-Omniversalism.com</span>';
>
> mysql_close();

As a matter of Code Style, you MAY want to consider doing:

$chosen = mysql_result($choose, 0, 0);

instead of creating a 1-element array and then accessing element 0 of
that array.

Some developers prefer to always do their PHP/mysql "the same"

Others prefer to make it clear when they are getting a singleton
database result, by using a different pattern of code.

-- 
Some people have a "gift" link here.
Know what I want?
I want you to buy a CD from some starving artist.
http://cdbaby.com/browse/from/lynch
Yeah, I get a buck. So?

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux