Jump to content

[SOLVED] PHP with MySQL - when not to use a while loop.


Siggles

Recommended Posts

Hi,

 

I want to get a figure from a database that I know will have one result. For example, the sum of a column. I then want to use that SUM in many places in a page. I understand that the while loop is often used with SQL queries but in this case I want teh variable to be used outside of a while loop, or is it that I don't use a while loop at all.

 

Up til now I have used...

 

<?
$result = mysql_query("SELECT COUNT(paidplayer) AS paidPlayers FROM users WHERE paidplayer = '2'");
while($row = mysql_fetch_array($result)){
$total = $row['paidPlayers'] * 20;
echo "<b>Current Dontaions: £".$total."</b>"; 
}
?>

 

Is it just a case of using global before the total variable. But surely this would cause problems in the event the query bringing more than one result. I have tried to look online what is the correct thing to do here but anything I see on queries and php, I see a while loop.

 

Regards

 

Siggles

Try this:

 

<?php

$total = array() // declare outside of array and it should be fine.

$result = mysql_query("SELECT COUNT(paidplayer) AS paidPlayers FROM users WHERE paidplayer = '2'");
while($row = mysql_fetch_array($result)){
$total = $row['paidPlayers'] * 20;
echo "<b>Current Dontaions: £".$total."</b>"; 

}
?>

 

Hope that helped???

Thank you. I also did it like this...

 

$result = mysql_query("SELECT COUNT(paidplayer) AS paidPlayers FROM users WHERE paidplayer = '2'");

$row = mysql_fetch_array($result);

$total = $row['paidPlayers'] * 20;

 

which is pretty obvious when I look at it. It is just that I always use while loops but then saw the flaw in them in this instance. I think that is because in most other cases I need to cycle through an array.

 

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.