[thelist] php/mysql: a more efficient method of doing this

Paul Cowan evolt at funkwit.com
Wed Apr 2 17:45:13 CST 2003

Hi Dunstan,
> I'm running a little bit of code that checks to see if an item is in a
user's > cart or not.
> If it's not it prints the '+' link, if it is then it prints the '-' link.

I'm not a PHP/mysql person, but you might find it more efficient to change

> $query = ("SELECT * FROM cart WHERE (userid = '$userid') AND (imageid
> = '$imageid')");

to this:

> $query = ("SELECT COUNT(*) AS NumberInCart FROM cart WHERE
> (userid = '$userid') AND (imageid = '$imageid')");

that way, you're selecting out one row with a count, rather than a variable
number of rows -- if userid/imageid is not a unique constraint on your table
(that is, one user with 500 dongle brackets in their cart means 500 rows
in the cart table, or something like that) it should be much better for

Make sure you then check the value of NumberInCart from the resulting
data set, not just count the number of rows -- as there will always be
1 row returned.

As pointed out by others, there are probably more efficient ways of doing
this full stop, but this should at least optimise your query a little.



More information about the thelist mailing list