PDA

View Full Version : CGI and MySQL !@#$


Han_Solo
03-14-2002, 11:39 AM
I'm trying to get Perl to connect to MySQL. But I get a "Can't call method "prepare" on an undefined value" Everytime I run the CGI.

Here is the test script. I would appreciate if someone pointed out the obvious "mistake" that I have.

THanks,

Han_Solo

#!/usr/local/bin/perl

#testing database connectivity

use DBI;
use CGI;
use CGI::Carp qw(fatalsToBrowser);

$database = "somedb";
$host = "localhost";
$user = "me";
$password = "apassword";

$query = new CGI;

print $query->header;


$dbh = DBI->connect("DBI:mysql:$database:$host", $user, $password);

$statement = "SELECT * FROM company order by coname";

$sth = $dbh->prepare($statement)
or die "Couldn't prepare the query: $sth->errstr\n";

$rv = $sth->execute
or die "Coudn't execute query: $dbh->errstr\n";

#$rv = $dbh->do($statement)
# or die "Can't execute $statement: $dbh->errstr\n";

print "<HTML>\n<HEAD>\n<TITLE>Companies in Database</TITLE>\n</HEAD>\n<BODY>\n";

print "<H1>Company Data</H1>\n";

while (@row = $sth->fetchrow) {
print "$row[0]\n";
}

$rc = $sth->finish;
$rc=$dbh->disconnect;

print "</BODY>\n</HTML>\n";

jrsmith
03-15-2002, 11:53 AM
for starters, i'd add an error check to your connect string:

$dbh = DBI->connect("DBI:mysql:$database:$host", $user, $password, {RaiseError => 1}) or die "Couldn't connect to db $database on $host: ", DBI->errstr();

since the "Can't call method 'prepare'..." error leads me to think you're not successfully connecting.

Han_Solo
03-15-2002, 12:06 PM
Hi jrsmith,

Thanks for the tip.

I added the line you suggested, and Bingo!

(Sheepesly)

Wrong username....

Thanks a million!!!!

Han_Solo