Page 1 of 1

mysql-php implementation not working according to logic

Posted: Tue May 13, 2008 1:19 pm
by definewebsites
Hi there,

I am trying to implement a small PHP script that can pick random content from a mysql database, and below is the description of the situation.

I have some content in a MySQL database, and I have a column that has a flag value for the content. If the flag value is '1', then the content is viable for retrieval from the database, but if '0' then it should not be retrieved. Below is the code that I am using:

Code: Select all

 
//...emitted code, i.e for opening database, connecting etc..
 
$query = "SELECT content1,content2 FROM table WHERE flag='1'";
$result = mysql_query($query) or die('Unable to run query');
$row = mysql_fetch_array($result, MYSQL_ASSOC);
 
while($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
$value1[] = $row['content1'];
$value2[] = $row['content2'];
}
$ran = rand(0,sizeof($value1)-1);
 
$val1 = $value1[$ran];
$val2 = $value2[$ran];
 
 
However, it does not work according to the logic I had when putting together this script. It does not seem to load the random content at all.

I went further to check the sizes of the arrays. The $row array had the right size as it should, but the $value1 and $value2 arrays did not have the proper size. I have spent days trying to work this out, and do not understand why its not working.

Any assistance would be greatly appreciated. :(

Thanks

Re: mysql-php implementation not working according to logic

Posted: Tue May 13, 2008 2:18 pm
by freeformer
If you're just looking to pick random content, then perhaps you should perform the logic of choosing which content to display in the SQL itself, and eliminate the need for trying to do it with PHP.

For example, you could use:

Code: Select all

SELECT content1,content2 FROM table WHERE flag='1' ORDER BY RAND()
to get a random selection of viable content items.

Re: mysql-php implementation not working according to logic

Posted: Tue May 13, 2008 6:49 pm
by definewebsites
Hi there,

Thanks for your response. It worked!!! yippy...thanks so much, I do appreciate... I had no clue that such a MYSQL function existed and I spent days trying to work it out in PHP.

Well, we learn everyday don't we?... :)

Cheers