The general rule is, when you are multiplying sums, each term of the first sum must multiply each term of the second and then added.
In particular, if both sums have two members, (ax+ b)(cx+ d), The "ax" must multiply both "cx" and "d" giving [itex]acx^2[/itex] and [itex]adx[/itex]. The "b" must multiply both "cx" and "d" giving [itex]bcx[/itex] and [itex]bd[/itex]. Adding those, [itex](ax+ b)(cx+ d)= acx^2+ adx+ bcx+ bd= acx^2+ (ad+ bc)x+ bd[/itex].
"FOIL" just makes sure all of those four multiplications are done. If we have two sums each with three terms, say (ax+ by+ c)(dx+ ey+ f), "each term in the first sum multiplies each term in the second sum", gives [itex]adx^2+ aexy+ afx+ bdxy+ bey^2+ bfy+ cdx+ cdy+ cf= adx^2+ (ae+ bd)xy+ bey^2+ (af+ cd)x+ (bf+ cd)y+ cf[/itex]