Optimized performance by changing SQL queries to exec_SELECTquery to get rid of double while/foreach loops when using exec_SELECTgetRows and moving parts of the WHERE clause of JOIN to ON
Changed the KEY of both MM tables after analysing the usage