NeonBlue
NeonBlue

Reputation: 1

Unable to insert into MySQL using Perl

I'm new to Perl and I have been trying this simple program to insert values into a database. I have two files, an HTML file that sends the form values to the Perl file. But I'm not able to perform any insertion or retrieval; I always get an empty page as the output.

HTML file:

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title>8th program</title>
    </head>
    <body>
        <form action="http://localhost:81/cgi-bin/8.pl" method="post">
            NAME:<input type="text" name="name"><br>
            AGE:<input type="text" name="age"><br>
            <input type="submit" value="submit">
        </form>
    </body>
</html> 

Perl file:

#!"C:\xampp\perl\bin\perl.exe"

print "Content-Type:text/html\n\n";

use CGI ':standard';
use DBI;

print "<html><head><title>insert</title></head>";

$dbh  = DBI->connect( "DBI:mysql:test", "root", " " );

$name = param( "name" );
$age  = param( "age" );

$qh   = $dbh->prepare( "insert into student values('$name','$age')" );
$qh->execute();

$qh = $dbh->prepare( "select * from student" );
$qh->execute();

print "<table border size=1>
       <tr>
       <th>Name</th>
       <th>Age</th>
       </tr>";

while ( ( $name, $age ) = $qh->fetchrow() ) {
    print "<tr><td>$name</td>
 <td>$age</td></tr>";
}

print "</table>";

$qh->finish();

$dbh->disconnect();

print "</html>";

Please help me with this.

Upvotes: 0

Views: 74

Answers (1)

Borodin
Borodin

Reputation: 126722

There is no DBI method fetchrow. In this instance it looks like you mean fetchrow_array

In addition, please take note of these points

  • On Windows systems, a shebang line is ignored except that any command switches specified there will be honoured. The path to the perl compiler / interpreter must be defined elsewhere

  • You must always

    use strict;
    use warnings 'all';
    

    at the top of every Perl program you write, and declare every variable as close as possible to its first point of use

  • You should use placeholders instead of interpolating parameters into SQL strings. Like this, for example

    my $qh = $dbh->prepare( 'INSERT INTO student (name, age) VALUES (?, ?)' );
    $qh->execute($name, $age);
    
  • It is wrong to call finish. The documentation has this

    Adding calls to "finish" after [a] loop that fetches all rows is a common mistake, don't do it, it can mask genuine problems like uncaught fetch errors.

Upvotes: 4

Related Questions