Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Hi all, I'm using Apache/2.0.47

Status
Not open for further replies.

tobyheywood

IS-IT--Management
Joined
Apr 20, 2001
Messages
122
Location
GB
Hi all,

I'm using Apache/2.0.47 (Win32) PHP/4.3.3 and for some very bizzare reason seem to be experiencing problems with foreach() statements.

Code:
$user = "username";
$pass = "password";
$loca = "localhost";
$datb = "web";
			
$link = mysql_connect($loca, $user, $pass);
if(! $link)
    die(mysql_error());
mysql_select_db($datb, $link)
    or die(mysql_error());
			
$queryrows = "SELECT * FROM quotes";
$result = mysql_query($queryrows, $link);
$rows = mysql_num_rows($result);
$randomid = rand(1,$rows);
// above all works to generate random id
$query = "SELECT quote FROM quotes where id = $randomid";
$result = mysql_query($query, $link);
$field = mysql_fetch_row($result);
foreach($field as $fact)
    print &quot;<p class=\&quot;body\&quot;><marquee>$fact</marquee></p>&quot;;
mysql_close($link);

The really weird thing is that it worked until I emptied the database that the info is being pulled from, now I have repopulated the database it still isn't working.

Can anyone make a suggestion as to why and also if you can suggest any better ways writing the above script it would be greatly appreciated.

TIA

Toby Heywood
 
OK folks,

I have worked out what the problem was... and for those interested a quick explaination follows.

The reason for the strange behaviour whilst trying to perform a foreach loop was caused by the use of the id field in the database.

The Id field is an auto-increment field and as such increments with each addition. My use of rand() specified the starting njumber of 1 and the maximum was specified by returning the maximum number of rows returned.

Once I had removed the existing rows from the database and then entered in new data it continued to increment the id field from the last id number used!

Therefore when I use &quot;SELECT quote FROM quotes where id = $randomid&quot; and $randomid contains anything below the first available id it falls over.

Hopefully that was of use to some people and now all that is required is to find out a way of making sure this doesn't happen again.



Toby Heywood
 
Code:
$query = &quot;SELECT quote FROM quotes ORDER BY RAND() LIMIT 1&quot;;
should work.

//Daniel
 
Daniel,

Thanks for that, the page also now loads a lot quicker as a result of the single query to the MySQL server.

Thanks again.

Toby Heywood
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top