Your code is a little messy. Firstly add:
use strict;
use warnings;
And work through those problems. You have variables declared out of scope then try to use them later, for example $table_name.This isn't going to work. Also, please consider the advice I gave last time you asked a databae question.
Update: On second look this is a little more messy that I thought. The advice about strict and warnings stands, see line 55, the sql statement uses a variable $ntime, which is never declared. Check for errors when doing anything with DBI, either with the RaiseError constructor, or manually each time.