Forum Moderators: open
#!/usr/bin/perl
#
print "content-type:text/html\n\n";
use DBI;
#
$db_name = 'ENTER YOUR DB NAME';
$db_host = 'localhost'; # or remote host
$sql_login = ENTER YOUR DB USER';
$sql_pass = 'ENTER YOUR DB PASS';
$conn_string = "DBI:mysql:$db_name";
if ($db_host) { $conn_string .= ":$db_host"; }
$dbh = DBI->connect("$conn_string",$sql_login,$sql_pass) or print("cannot connect to database");
#
# this is an array = @ has a diff. meaning in Perl
@lines = (
'this is a line without a comma',
'this, line, has, inline, commas',
'Here\'s a comma,',
'this is one with spaces after it , ',
'here\'s another,',
'and another,',
'we don\'t need no steeking commas.'
);
#
$select = qq|create temporary table replace_test (id int(11) primary key auto_increment, txtval text);|;
$sth = $dbh->prepare("$select");
$rv = $sth->execute or print($dbh->errstr());
$sth->finish;
#
foreach $line (@lines) {
$line =~ s/'+/''/g; # this part is for the internal quotes
$select = qq|insert into replace_test (txtval) values ('$line');|;
$sth = $dbh->prepare("$select");
$rv = $sth->execute or print($dbh->errstr());
$sth->finish;
}
#
print "replacing:<br>\n";
$select = qq|select id,txtval from replace_test;|;
$sth = $dbh->prepare("$select");
$rv = $sth->execute or print($dbh->errstr());
while (($id,$val) = $sth->fetchrow_array) {
$val =~ s/,\s*$//g; # The actual removal of the end comma
$val =~ s/'+/''/g; # this part is for the internal quotes - nothing to do with the task
$select = qq|update replace_test set txtval='$val' where id=$id;|;
$sth2 = $dbh->prepare("$select");
$rv2 = $sth2->execute or print($dbh->errstr());
$sth2->finish;
}
$sth->finish;
#
print "Did it work?<br>\n";
#
$select = qq|select txtval from replace_test;|;
$sth = $dbh->prepare("$select");
$rv = $sth->execute or die($dbh->errstr());
while ($val = $sth->fetchrow_array) { print "$val<br>\n"; }
$sth->finish;
#
$select = qq|drop table replace_test;|;
$sth = $dbh->prepare("$select");
$rv = $sth->execute or print($dbh->errstr());
$sth->finish;
print "Done.<br>\n";