mmcb Posted January 24, 2007 Share Posted January 24, 2007 Hello again,I have a new problem for you all. I have a MySQL table and want to return certain records (no problem), but I also want MySQL to generate a random number. This is what I'm using:[code]SELECT DesignID, DesignName, (FLOOR(1 + RAND() * 12)) AS Location FROM `tbldesigns` WHERE MenuID="something";[/code]This works except that I sometimes get duplicates in the "Location" field. Is there anyway to do the same thing without getting duplicates?Cheers,MMCB Link to comment https://forums.phpfreaks.com/topic/35581-mysql-random-number-problem/ Share on other sites More sharing options...
Psycho Posted January 24, 2007 Share Posted January 24, 2007 I would suggest doing the random numbers in the PHP after you get the results. Assuming you will be looping through the records to display/act on them you could do something like this:[code]<?php$randNumbers = array();while ($row = mysql_fetch_array($results)) { $newNo=""; while ($newNo=="" || in_array ($newNo, $randNumbers)) { $newNo = rand(1,12); } $randNumbers[] = $newNo; //Display row resultrs and the random number}?>[/code]Of couorse you would get stuck in an infinite loop if there were more than 12 results, so you would want to add an exception handler for that. Link to comment https://forums.phpfreaks.com/topic/35581-mysql-random-number-problem/#findComment-168522 Share on other sites More sharing options...
snowrhythm Posted January 24, 2007 Share Posted January 24, 2007 yeah, you also might want to throw in a "DINSTINCT" in front of "LOCATION" in the SQL string... Link to comment https://forums.phpfreaks.com/topic/35581-mysql-random-number-problem/#findComment-168529 Share on other sites More sharing options...
Psycho Posted January 25, 2007 Share Posted January 25, 2007 [quote author=snowrhythm link=topic=123897.msg512751#msg512751 date=1169677349]yeah, you also might want to throw in a "DINSTINCT" in front of "LOCATION" in the SQL string...[/quote]DISTINCT won't work in this situation as it is not a field he is pulling from the table. I tried it out of curiosity and no go. Link to comment https://forums.phpfreaks.com/topic/35581-mysql-random-number-problem/#findComment-168584 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.