I am trying to create a table in MySQL based on user input. Ideally, the Perl script would connect to the database and create a table with a variable that was received from the user. Here's my script:
print "Please enter a name for the table: ";
$tableName = <>;
chomp($tableName);
&createTable ($tableName);
sub createTable
{
use DBI;
my $platform = "mysql";
my $database = "example";
my $host = "localhost";
my $user = "user";
my $pw = "pw";
my $dsn = "dbi:$platform:$database:$host";
my $dbh = DBI->connect($dsn, $user, $pw) or die "Unable to connect: $DBI::errstr\n";
$dbh->do("DROP TABLE IF EXISTS $_");
$dbh->do("CREATE TABLE $table (column VARCHAR(17))");
$dbh->disconnect;
}
But when I execute the script, and enter a value (let's say 'test'), it blurts this back to me:
DBD::mysql::db do failed: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1 at /path/to/scripts/dbTest.pl line 28, <> line 2.
DBD::mysql::db do failed: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '(column VARCHAR(17))' at line 1 at /path/to/scripts/dbTest.pl line 29, <> line 2.
Line 28 is the DROP command, and line 29 is the CREATE command. I've checked my syntax plenty of times, but I'm not seeming to get where the error is at. Am I overlooking something so simple..?
Try that :
use warnings; use strict;
use DBI;
print "Please enter a name for the table: ";
$tableName = <>;
chomp($tableName);
createTable($tableName);
sub createTable {
my $table = shift;
my $platform = "mysql";
my $database = "example";
my $host = "localhost";
my $user = "user";
my $pw = "pw";
my $dsn = "dbi:$platform:$database:$host";
my $dbh = DBI->connect($dsn, $user, $pw)
or die "Unable to connect: $DBI::errstr\n";
$dbh->do("DROP TABLE IF EXISTS $table");
$dbh->do("CREATE TABLE $table (column VARCHAR(17))");
$dbh->disconnect;
}
You can't use $_
like that in your functions. You have to deal with @_
instead (or use shift
like I does). See perldoc perlsub