Siggles Posted July 14, 2008 Share Posted July 14, 2008 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 Link to comment https://forums.phpfreaks.com/topic/114636-solved-php-with-mysql-when-not-to-use-a-while-loop/ Share on other sites More sharing options...
waynew Posted July 14, 2008 Share Posted July 14, 2008 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??? Link to comment https://forums.phpfreaks.com/topic/114636-solved-php-with-mysql-when-not-to-use-a-while-loop/#findComment-589395 Share on other sites More sharing options...
Siggles Posted July 14, 2008 Author Share Posted July 14, 2008 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. Link to comment https://forums.phpfreaks.com/topic/114636-solved-php-with-mysql-when-not-to-use-a-while-loop/#findComment-589398 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.