Both scripts are missing an additional JOIN on salesorders.debtorno=custbranch.debtorno which could cause a return of multiple records in the results from $sql3.
Of course salesorders.debtorno must be added to $sql to fulfill and support the above JOIN.