munish
munish

Reputation: 4644

DBD::mysql fetchrow_array failed: fetch() without execute()?

I am getting the error for the following code:

#!C:/usr/bin/perl -w

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


print "content-type: text/html; charset=iso-8859-1\n\n";

my $q=new CGI;
my $ename=$q->param('ename');
my $email=$q->param('email');

print $q->header;
print "<br>$ename<br>";


#connect to database.
my $dbh = DBI->connect("DBI:mysql:database=test;host=localhost","root","mukesh",
          {'RaiseError' => 1});

eval {$dbh->do("CREATE TABLE IF NOT EXISTS emp (ename VARCHAR(20), email VARCHAR(50))")};
print "<br>creating table emp failed: $@<br>" if $@;


my $sql="INSERT INTO emp(ename,email) values('$ename','$email')";

my $sth = $dbh->prepare($sql) or die "Can't prepare $sql:$dbh->errstrn";
#pass sql query to database handle


my $rv = $sth->execute() or die "can't execute the query: $sth->errstrn";

my @row;
while (@row = $sth->fetchrow_array) {
print join(", ",@row);
}

$sth->finish();
$dbh->disconnect();

if ($rv==1){
print "<br>Record has been successfully updated !!!<br>";
}else{
print "<br>Error!!while inserting record<br>";
exit;
}

Please suggest.what is the problem. it works fine if i remove this piece of code.

my @row;
while (@row = $sth->fetchrow_array) {
print join(", ",@row);
}

Upvotes: 0

Views: 2062

Answers (1)

raina77ow
raina77ow

Reputation: 106375

You're trying to use the common SELECT cycle in DBI - prepare, execute, fetch - for a non-select query (INSERT in your case). What you probably should do instead is check the result of execute directly. Quoting the doc:

For a non-SELECT statement, execute returns the number of rows affected, if known. If no rows were affected, then execute returns "0E0", which Perl will treat as 0 but will regard as true. Note that it is not an error for no rows to be affected by a statement. If the number of rows affected is not known, then execute returns -1.

Upvotes: 4

Related Questions