# Field Calculation

3 replies to this topic

### #1 shaunk

shaunk
• New Members
• Newbie
• 3 posts

Posted 22 March 2006 - 06:18 PM

Hopefully this is easy for womeone else:-

I've recently set up a database that contains a numbet of fields, say for arguments sake they are field1, field2, field3 etc....

Want I want to do is make field5 equal a value of the latest value entered in field1 minus the first value entered in field1.

ie: in the column field1 the first or starting entery is say 50 and as users interact with the database this value increases dependant on user input (don't worry about why) so the last value in column field1 could be say 65. I want to calculate the difference (15) and enter it into a new field.

I seem to be running in to problems with a syntax or something because I've tried many combinations like the following:-

<?php \$firstvalue = SELECT field1 FROM databasename ORDER BY field1 ASC LIMIT 1 ;
\$secondvalue = SELECT field1 FROM databasename ORDER BY field1 DESC LIMIT 1 ;
\$valuerequired = \$secondvalue - \$firstvalue
echo "\$valuerequired" ?>

Any help will be much appriciated I've run out of ideas.

Thanks Shaun

### #2 obsidian

obsidian
• Staff Alumni
• 3,202 posts
• LocationSeattle, WA

Posted 22 March 2006 - 06:22 PM

you're close, but when you simply do a query, it returns a reference to the results, not the results themselves. so, you'd need to do this:
```\$first = mysql_result(mysql_query("SELECT field1 FROM tableName ORDER BY field1 ASC LIMIT 1"), 0, 'field1');
\$last = mysql_result(mysql_query("SELECT field1 FROM tableName ORDER BY field1 DESC LIMIT 1"), 0, 'field1');

echo (\$last - \$first);
```

You can't win, you can't lose, you can't break even... you can't even get out of the game.

```<?php
while (count(\$life->getQuestions()) > 0)
{   \$life->study(); } ?>```
LINKS: PHP: Manual MySQL: Manual PostgreSQL: Manual (X)HTML: Validate It! CSS: A List Apart | IE bug fixes | Zen Garden | Validate It! JavaScript: Reference Cards RegEx: Everything RegEx

### #3 shaunk

shaunk
• New Members
• Newbie
• 3 posts

Posted 22 March 2006 - 07:45 PM

Fantastic, thanks

### #4 Barand

Barand
• Moderators
• Sen . ( ile || sei )
• 18,017 posts

Posted 22 March 2006 - 09:44 PM

If the values always increase you could use a single query

```\$result = mysql_query ("SELECT MIN(field1) as first, MAX(field1) as last FROM tablename");

echo mysql_result(\$result, 0, 'last') - mysql_result(\$result, 0, 'first');```

If you are still using mysql_ functions, STOP! Use mysqli_ or PDO. The longer you leave it the more you will have to rewrite.