I have developed a fairly ramshackle PHP/JavaScript Reward system for my school’s VLE.
The main bulk of the work is done on a transactions table which has the following fields:
Transaction_ID, Datetime, Giver_ID, Recipient_ID, Points, Category_ID, Reason
The idea is that if I, as a member of staff, give a student some Reward Points, an entry such as this is inserted into the database:
INSERT INTO `transactions` (`Transaction_ID`, `Datetime`, `Giver_ID`, `Recipient_ID`, `Points`, `Category_ID`, `Reason`) VALUES
(60332, '2012-02-22', 34985, 137426, 5, 5, 'Excellent volcano homework.');
This worked fine – but I didn’t really consider just how much the system would be used. I now have over 72,000 transactions in this table.
As such, a few of my pages are starting to slow down. For instance, when staff try to allocate points, my system runs a command to get the member of staff’s total point allocation and other snippets of information. This appears to be displaying rather slowly, and looking at the MySQL statement/accompanying PHP code, I think this could be much more efficient.
function getLimitsAndTotals($User_ID) {
$return["SpentTotal"] = 0;
$return["SpentWeekly"] = 0;
$sql = "SELECT *
FROM `transactions`
WHERE `Giver_ID` =$User_ID";
$res = mysql_query($sql);
if (mysql_num_rows($res) > 0) {
while ($row = mysql_fetch_assoc($res)) {
$return["SpentTotal"] += $row["Points"];
$transaction_date = strtotime ($row["Datetime"]);
if ($transaction_date > strtotime( "last sunday" )) {
$return["SpentWeekly"] += $row["Points"];
}
}
}
return $return;
}
As such, my question is twofold.
- Can this specific code be optimised?
- Can I employ any database techniques – full text indexing or the like – to further optimise my system?
EDIT: RE Indexing
I don’t know anything about indexing, but it looks like my transactions table does actually have an index in place?

Is this the correct type of index?
Here is the code for table-creation:
CREATE TABLE IF NOT EXISTS `transactions` (
`Transaction_ID` int(9) NOT NULL auto_increment,
`Datetime` date NOT NULL,
`Giver_ID` int(9) NOT NULL,
`Recipient_ID` int(9) NOT NULL,
`Points` int(4) NOT NULL,
`Category_ID` int(3) NOT NULL,
`Reason` text NOT NULL,
PRIMARY KEY (`Transaction_ID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=74927 ;
Thanks in advance,
Make sure
Giver_IDis indexed. Try also running the strtotime outside of your while loop as I imagine its an expensive operation to be running 72,000 times.Also consider running
UNIX_TIMESTAMP(Datetime) AS datetime_timestampin your SQL instead of getting it out as a string and running another expensive strtotime operation. You can then simply run:(if your column is of type DATE, of course!)