PDA

View Full Version : How to make this efficient?


iceflyin
11-12-2007, 10:33 AM
My first random tip selection code had an issue of coming up with blank results if the sex didn't match.


$tipData = mysql_query("SELECT * FROM tips WHERE tid >= (SELECT FLOOR( MAX(tid) * RAND()) FROM tips) AND forsex=$sex ORDER BY tid LIMIT 1;", $conn) or die ('Rand select failed');


Now, I'm using this workaround to make sure it finds a tip. But... It may take 1-3 queries to lock down on one. Any ideas how to make this more efficient?


$gotTip = false;
while ($gotTip == false){
//Note, inefficent because it may search around a bit for a girl or guy tip.
$tipData = mysql_query("SELECT * FROM tips WHERE tid >= (SELECT FLOOR( MAX(tid) * RAND()) FROM tips) AND forsex=$sex ORDER BY tid LIMIT 1;", $conn) or die ('Rand select failed');
$tipInfo = mysql_fetch_array($tipData);
if (isset($tipInfo[text]{2})){
$gotTip= true;
}
}

guelphdad
11-12-2007, 02:13 PM
first tip add the .mysql_error() to your die.

Second why not just ensure a match with the sex field in the first place. Do you actually use NULL values or do you use empty strings?

put an AND condition in there that checks for an empty string or NULL and then you won't get one of those.