FRIHOST • FORUMS • SEARCH • FAQ • TOS • BLOGS • COMPETITIONS
You are invited to Log in or Register a free Frihost Account!


Subtracting one value from another from MySQL result





welshsteve
Hi everyone. I've got a script that outputs league tables from a MySQL database. I cannot figure out how to set certain fields in the data table to calculate based on other fields e.g. if a team has played 10 matches and won 6, I'd need to set the "Lost" field to "Played - Won". So I thought I could do it on the output in PHP instead, but I've never used maths in php before. I tried the below but it doesn't seem to work and messes everything up. Is anybody able to assist at all?

Code:

<?php
$con = mysql_connect("SERVER","USERNAME","PASSWORD");
if (!$con)
  {
  die('Could not connect: ' . mysql_error() . '<br /><br />In english *smile* there is a problem with the web hosting server');
  }

mysql_select_db("DBNAME", $con);

$sql = "SELECT * FROM Premier ORDER BY Pts DESC , W DESC , Pld , Team";
$result = mysql_query($sql);
if (!$result)
echo mysql_error();

echo "<h2>Premier Division</h2>
<table>
<tr>
<th>Team</th>
<th>Pld</th>
<th>Won</th>
<th>Lost</th>
<th>PD</th>
<th>Pts</th>
</tr>";
      
while($row = mysql_fetch_array($result))
  {
   echo "<tr>";
   echo "<td>&nbsp;" . $row['Team'] . "</td>";
   echo "<td>" . $row['Pld'] . "</td>";
   echo "<td>" . $row['W'] . "</td>";
   echo "<td>" . $row['Pld'] - $row['W'] . "</td>";
   echo "<td>" . $row['Pts_Deducted'] . "</td>";
   echo "<td>" . $row['Pts'] . "</td>";
  echo "</tr>";
  }
echo "</table>";

mysql_close($con);
?>
Peterssidan
You will probably have to surround the Played - Won calculation inside parenthesis.
Code:
echo "<td>" . ($row['Pld'] - $row['W']) . "</td>";
rvec
you could do it in the query like this:
Code:
SELECT *, Pld-W AS L FROM Premier ....


Don't get why your version wouldn't work though. () shouldn't make a difference.
Could you check if var_dump($row) does have all the right values? (in the while loop).
welshsteve
Thanks, that seems to have sorted it. Smile
Related topics
Question about a php and mysql script.
Defalut Value in MySql
An Example to mySQL class
Need Help integrating php variable into mySQL SELECT query
Mysql error: Warning: mysql_num_rows():
Trouble with submitting an integer to MySQL
[php scripts ] phpweather&email
Database/PHP/Cron Jobs [Resolved]
[solved] Weird mysql error
[mySQL] Error I cannot Debug
mysql problems
Can΄t connect to my database with php-nuke
Mysql Error
could use some help..simple one line issue
Reply to topic    Frihost Forum Index -> Scripting -> Php and MySQL

FRIHOST HOME | FAQ | TOS | ABOUT US | CONTACT US | SITE MAP
© 2005-2011 Frihost, forums powered by phpBB.