This happens all the time.
when your loop goes through, it will end up with an extra comma on the end, remove it with rtrim() after your loop is finished
PHP Code:
$sql = rtrim($sql,", ");
Also, after that is all done, you have open a paranthesis(sp) but not closed it, look right after the CREATE TABLE, so just append a close paranthesis to the end and you should be pretty well good to go.