mysql-php implementation not working according to logic

Questions about the MySQL, PostgreSQL, and most other databases, as well as using it with PHP can be asked here.

Moderator: General Moderators

Post Reply
definewebsites
Forum Newbie
Posts: 19
Joined: Thu May 01, 2008 9:51 pm

mysql-php implementation not working according to logic

Post 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
User avatar
freeformer
Forum Newbie
Posts: 14
Joined: Tue May 13, 2008 1:54 pm
Location: UK

Re: mysql-php implementation not working according to logic

Post 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.
definewebsites
Forum Newbie
Posts: 19
Joined: Thu May 01, 2008 9:51 pm

Re: mysql-php implementation not working according to logic

Post 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
Post Reply