perl script to query database | Familiar Sight | | Join Date: Sep 2008
Posts: 236
| |
Hi All,
I am doing a connection to database from perl to mysql via apache. Apache is configured correctly.
Mysql username is root and password is mysql1, and database name is test.
when I type in url 127.0.0.1/cgi-bin/dbconn.pl, it showed internal server error 500. And errors in apache section a) below and errors in access. The samples table is created under test, residing in mysql database.
Tried to triple check and the configurations looks fine. Anyone can kindly assist? Thanks in advance
Andrew
dbconn.pl -
-
#!c:\perl\bin\perl.exe -w
-
#!/usr/bin/perl -w
-
-
use DBI;
-
$dbh = DBI->connect('dbi:mysql:test','root','mysql1')
-
or die "Connection Error: $DBI::errstr\n";
-
$sql = "select * from samples";
-
$sth = $dbh->prepare($sql);
-
$sth->execute
-
or die "SQL Error: $DBI::errstr\n";
-
while (@row = $sth->fetchrow_array) {
-
print "@row\n";
-
-
}
-
-
a) apache error log
-
[Mon Oct 06 01:07:39 2008] [error] [client 127.0.0.1] Premature end of script headers: dbconn.pl
-
[Mon Oct 06 01:07:39 2008] [error] [client 127.0.0.1] install_driver(mysql) failed: Can't locate DBD/mysql.pm in @INC (@INC contains: C:/perl/site/lib C:/perl/lib .) at (eval 4) line 3.\r
-
[Mon Oct 06 01:07:39 2008] [error] [client 127.0.0.1] Perhaps the DBD::mysql perl module hasn't been fully installed,\r
-
[Mon Oct 06 01:07:39 2008] [error] [client 127.0.0.1] or perhaps the capitalisation of 'mysql' isn't right.\r
-
[Mon Oct 06 01:07:39 2008] [error] [client 127.0.0.1] Available drivers: CSV, DBM, ExampleP, File, Gofer, ODBC, Oracle, Proxy, SQLite, Sponge.\r
-
[Mon Oct 06 01:07:39 2008] [error] [client 127.0.0.1] at D:/Program Files/Apache Software Foundation/Apache2.2/cgi-bin/dbconn.pl line 5\r
|  | Moderator | | Join Date: Jul 2007 Location: Arkansas
Posts: 900
| | | re: perl script to query database
You will need to print the headers before you try and print anything to the screen. Add this line of code to your script. - print "Content-type: text/html", "\n\n";
If you are using the CGI.pm then you can do the following. - use CGI;
-
my $q = CGI->new();
-
-
print $q->header();
Also to help debug you can add the following as well. -
use CGI::Carp qw/fatalsToBrowser/;
Edit: It appears that you don't have DBD::Mysql installed. This a must when you are connecting to a MySQL DB.
--Kevin
|  | Moderator | | Join Date: Jul 2007 Location: Arkansas
Posts: 900
| | | re: perl script to query database
Here is a link to a resource to help determining some of the common problems when you get the dreaded 500 error.
--Kevin
| | Familiar Sight | | Join Date: Sep 2008
Posts: 236
| | | re: perl script to query database
Hi Kevin,
Thanks again. Will try out what you mentioned...
I was using this link http://perl.about.com/od/perltutorials/a/perlmysql_3.htm
Cheers...
Andrew
| | Familiar Sight | | Join Date: Sep 2008
Posts: 236
| | | re: perl script to query database
Hi...
I tried out the below script, this time the url 127.0.0.1/cgi-bin/dbconn.pl printed out blank screen(no more screen error). I had installed dbd-mysqlpp.
Apache error log showed 500 and 543 errors. Apache access log showed 127.0.0.1 - - [06/Oct/2008:08:35:18 -0700] "GET /cgi-bin/dbconn.pl HTTP/1.1" 200 -
Kindly assist. I will however try some other methods further.
Btw, what is CGI PM? Also, the print "Content-type: text/html", "\n\n"; which line I should put in?
Thanks and Best Rgds,
Andrew -
-
#!c:\perl\bin\perl.exe -w
-
#!/usr/bin/perl -w
-
-
-
use DBI;
-
-
use CGI;
-
my $q = CGI->new();
-
-
print $q->header();
-
-
-
$dbh = DBI->connect('dbi:mysql:test','root','mysql1')
-
or die "Connection Error: $DBI::errstr\n";
-
$sql = "select * from samples";
-
$sth = $dbh->prepare($sql);
-
$sth->execute
-
or die "SQL Error: $DBI::errstr\n";
-
print "Content-type: text/html", "\n\n";
-
-
while (@row = $sth->fetchrow_array) {
-
print "@row\n";
-
-
-
}
-
-
|  | Expert | | Join Date: Jan 2007 Location: Southern California USA
Posts: 4,091
| | | re: perl script to query database
try changing 'root' to 'localhost'
|  | Moderator | | Join Date: Jul 2007 Location: Arkansas
Posts: 900
| | | re: perl script to query database
I did not even look at the connection string. Here is an example of a connection string that works. - my ($dbh, $data_source);
-
my $mysql_server_name = 'localhost';
-
my $mysql_database_name = 'xxx';
-
my $mysql_user_name = 'root';
-
my $mysql_password = 'xxx';
-
-
my $data_source = 'DBI:mysql:' . $mysql_database_name . ':' . $mysql_server_name;
-
my $dbh = DBI->connect( $data_source, $mysql_user_name, $mysql_password, {PrintError=>1}) || die "$DBI::errstr";
--Kevin
| | Newbie | | Join Date: Oct 2008 Location: Cochin
Posts: 4
| | | re: perl script to query database
Hi,
Make sure that there are entries there in the database, otherwise the result would be a blank screen again.
search for Mysql+connect +perl in google and you get thousands of snippets which you can use.
| | Familiar Sight | | Join Date: Sep 2008
Posts: 236
| | | re: perl script to query database
Hi All,
I tried both methods and it show the content type Content-type: text/html in the url 127.0.0.1/cgi-bin/dbconn2.pl. And alternately it shows internal error.
apache access show status 200 ok, but it showed error 25.
my database is test, user and password correct. It showed root@localhost, with mysql, test db tables. both mysql and test got the same samples rows.
What could be wrong, tried many different ways and scratching head whole nite. Thanks.
Code below : -
#!c:\perl\bin\perl.exe -w
-
#!/usr/bin/perl -w
-
-
use DBI;
-
use mysqlpp;
-
use apachemysql;
-
-
print "Content-type: text/html", "\n\n";
-
-
my ($dbh, $data_source);
-
my $mysql_server_name = 'localhost';
-
my $mysql_database_name = 'test';
-
my $mysql_user_name = 'root';
-
my $mysql_password = 'mysql1';
-
-
my $data_source = 'DBI:mysql:' . $mysql_database_name . ':' . $mysql_server_name;
-
my $dbh = DBI->connect( $data_source, $mysql_user_name, $mysql_password, {PrintError=>1}) || die "$DBI::errstr";
-
-
-
$sql = "select * from samples";
-
$sth = $dbh->prepare($sql);
-
$sth->execute
-
or die "SQL Error: $DBI::errstr\n";
-
-
print "testing output : $sth ";
-
print "Press the ENTER key to exit program ...";
-
$pause = <STDIN>; #Like a PAUSE statement in DOS .bat files
-
-
exit;
-
-
|  | Moderator | | Join Date: Jul 2007 Location: Arkansas
Posts: 900
| | | re: perl script to query database
Here is your code reworked a bit. Be sure to check out the DBI documentation if you see things you don't understand on the DBI part of the script. This script is also assuming that you are accessing it via a web browser. - #! /usr/bin/perl -T
-
-
use strict;
-
use warnings;
-
-
use DBI;
-
use CGI::Carp qw/fatalsToBrowser/;
-
-
print "Content-type: text/html", "\n\n";
-
-
my ($dbh, $data_source);
-
my $mysql_server_name = 'localhost';
-
my $mysql_database_name = 'test';
-
my $mysql_user_name = 'root';
-
my $mysql_password = '';
-
-
my $data_source = 'DBI:mysql:' . $mysql_database_name . ':' . $mysql_server_name;
-
my $dbh = DBI->connect( $data_source, $mysql_user_name, $mysql_password, {RaiseError=>1}) || die "$DBI::errstr";
-
-
-
my $sql = $dbh->prepare(qq{SELECT * FROM samples});
-
$sql->execute();
-
-
while (my @data = $sql->fetchrow_array()) {
-
-
# Print the date from the first two columns in the table
-
print $data[0], "\t", $data[1], "<br>";
-
}
-
-
-
1;
--Kevin
| | Familiar Sight | | Join Date: Sep 2008
Posts: 236
| | | re: perl script to query database
Hi Guru Kevin,
Thanks. But Still Cannot Work after trying. got apache Errors 500 and 543. Also, the url 127.0.0.1/cgi-bin/db.pl showed is :
Software error:
install_driver(mysql) failed: Can't locate DBD/mysql.pm in @INC (@INC contains: C:/perl/site/lib C:/perl/lib .) at (eval 5) line 3.
Perhaps the DBD::mysql perl module hasn't been fully installed,
or perhaps the capitalisation of 'mysql' isn't right.
Available drivers: CSV, DBM, ExampleP, File, Gofer, ODBC, Oracle, Proxy, SQLite, Sponge, mysqlPP.
at D:/Program Files/Apache Software Foundation/Apache2.2/cgi-bin/db.pl line 19
For help, please send mail to the webmaster (admin@gateway.2wire.net), giving this error message and the time and date of the error. -
#!c:\perl\bin\perl.exe
-
#!/usr/bin/perl -T
-
-
use strict;
-
use warnings;
-
use mysqlpp;
-
-
use DBI;
-
use CGI::Carp qw(fatalsToBrowser);
-
-
print "Content-type: text/html", "\n\n";
-
-
my ($dbh, $data_source);
-
my $mysql_server_name = 'localhost';
-
my $mysql_database_name = 'test';
-
my $mysql_user_name = 'root';
-
my $mysql_password = 'mysql1';
-
-
my $data_source = 'DBI:mysql:' . $mysql_database_name . ':' . $mysql_server_name;
-
my $dbh = DBI->connect( $data_source, $mysql_user_name, $mysql_password, {RaiseError=>1}) || die "$DBI::errstr";
-
-
-
my $sql = $dbh->prepare(qq{SELECT * FROM samples});
-
$sql->execute();
-
-
while (my @data = $sql->fetchrow_array()) {
-
-
# Print the date from the first two columns in the table
-
print $data[0], "\t", $data[1], "<br>";
-
}
-
-
-
1;
-
-
-
| | Familiar Sight | | Join Date: Sep 2008
Posts: 236
| | | re: perl script to query database
I am using windows perl and windows apache btw. Cheers...
|  | Moderator | | Join Date: Jul 2007 Location: Arkansas
Posts: 900
| | | re: perl script to query database
Test the script with this line omitted or commented out. Just to see what happens.
Also, run this script. What it will do is tell you if you have the DBI and DBD::mysql modules are installed and the version number of each. It really appears that you do not have the DBD::mysql module installed. - #!/usr/bin/perl
-
-
use strict;
-
use warnings;
-
-
use CGI;
-
use CGI::Carp qw/fatalsToBrowser/;
-
use DBI;
-
use DBD::mysql;
-
-
my $q = CGI->new;
-
-
print $q->header();
-
print "$ENV{'DOCUMENT_ROOT'} has DBI Version: " .$DBI::VERSION. " installed on it.<br>";
-
print "$ENV{'DOCUMENT_ROOT'} has DBD::mysql Version: " .$DBD::mysql::VERSION. " installed on it.<br>";
-
-
-
1;
--Kevin
|  | Expert | | Join Date: Jan 2007 Location: Southern California USA
Posts: 4,091
| | | re: perl script to query database
As mentioned previously in this thread, you need to install DBD::Mysql
|  | Expert | | Join Date: Jan 2007 Location: Southern California USA
Posts: 4,091
| | | re: perl script to query database | | Familiar Sight | | Join Date: Sep 2008
Posts: 236
| | | re: perl script to query database
Hi Kevin,
scan through and searched few times...I cant find this module DBD::Mysql, i can only install mysqlpp module. It is strange...
Thanks,
Andrew
|  | Expert | | Join Date: Jan 2007 Location: Southern California USA
Posts: 4,091
| | | re: perl script to query database Quote:
Originally Posted by happyse27 Hi Kevin,
scan through and searched few times...I cant find this module DBD::Mysql, i can only install mysqlpp module. It is strange...
Thanks,
Andrew Did you read the thread I linked for you?
| | Familiar Sight | | Join Date: Sep 2008
Posts: 236
| | | re: perl script to query database
Hi Kevin,
Thanks again. I read throught the thread you gave. And it is working now. http://bytes.com/forum/thread840298...3A%3Amysql.html Installed mysql module, the exact name is use dbd::mysql in windows perl script. Cheers!!! again.
Try this:
START>>PROGRAMS>>ACTIVEPERL>>PPM
Once thePPM GUI is running click on the EDIT tab, then PREFERENCES, then click on the REPOSITORIES tab then on the SUGGESTED tab select "uwinnipeg" and click on ADD. After the uwinnipeg packages are viewable see if DBD-mysql is listed. If not try the same thing and add "bribes" to the list of repositories. Once the DBD-mysql module is listed mark it for install then install it. Read the PPM help files if my instructions are confusing.
--------------------------------------------------------------------------------
complete code -
#!c:\perl\bin\perl.exe
-
#!/usr/bin/perl -T
-
-
use strict;
-
use DBD::mysql;
-
use DBI;
-
use CGI::Carp qw(fatalsToBrowser);
-
-
print "Content-type: text/html", "\n\n";
-
-
my ($dbh, $data_source);
-
my $mysql_server_name = 'localhost';
-
my $mysql_database_name = 'test';
-
my $mysql_user_name = 'root';
-
my $mysql_password = 'mysql1';
-
-
my $data_source = 'DBI:mysql:' . $mysql_database_name . ':' . $mysql_server_name;
-
my $dbh = DBI->connect( $data_source, $mysql_user_name, $mysql_password, {RaiseError=>1}) || die "$DBI::errstr";
-
-
-
my $sql = $dbh->prepare(qq{SELECT * FROM samples});
-
$sql->execute();
-
-
while (my @data = $sql->fetchrow_array()) {
-
-
# Print the date from the first two columns in the table
-
print $data[0], "\t", $data[1], "<br>";
-
}
-
-
-
1;
-
|  | Expert | | Join Date: Jan 2007 Location: Southern California USA
Posts: 4,091
| | | re: perl script to query database
Good. In the future please read what people post and try and follow any instructions you are given. Sometimes you are not reading all the replies or doing what people ask. Since we are trying to help you, you need to try and follow instructions and any other requests or advise posted.
Regards,
Kevin
| | Familiar Sight | | Join Date: Sep 2008
Posts: 236
| | | re: perl script to query database
Hi...
sorry Kevin, I missed out the instructions sometimes as I do panic and scramble for more information. Will be more attentive. if not missed the instruction I also wanted and would have wanted to resolve the matter earlier, alot of time wasted in resolving bugs...
Btw, if I use to use OOP(object based programming), which are the things to look out for to install, which references sites to read and what is the way to make sure I can re-use codes...
Cheers...
Andrew
| | Familiar Sight | | Join Date: Sep 2008
Posts: 236
| | | re: perl script to query database
Hi All,
Two questions to consult...
1) I can insert database information successfully using insert below in the code(see code below).
2) but I cant display any output in html. Any idea? I got the error below (see section a below).
The script which part is going wrong? Also the 1; not sure how to resolve? Thanks in advance again.
Cheers...
Andrew
a) Internal Server Error
The server encountered an internal error or misconfiguration and was unable to complete your request.
Please contact the server administrator, admin@gateway.2wire.net and inform them of the time the error occurred, and anything you might have done that may have caused the error.
More information about this error may be available in the server error log. -
-
#!c:\perl\bin\perl.exe
-
#!/usr/bin/perl -T
-
-
use strict;
-
use warnings;
-
use CGI;
-
use CGI::Carp qw/fatalsToBrowser/;
-
use File::Basename;
-
-
use DBD::mysql;
-
use DBI;
-
-
-
$CGI::POST_MAX = 1024 * 5000; #adjust as needed (1024 * 5000 = 5MB)
-
$CGI::DISABLE_UPLOADS = 0; #1 disables uploads, 0 enables uploads
-
-
my $query = CGI->new;
-
-
unless ($CGI::VERSION >= 2.47) {
-
error('Your version of CGI.pm is too old. You must have verison 2.47 or higher to use this script.')
-
}
-
-
-
#SECTION B
-
#=========================================
-
#Database initialization and initial query
-
my ($dbh, $data_source);
-
my $mysql_server_name = 'localhost';
-
my $mysql_database_name = 'test';
-
my $mysql_user_name = 'root';
-
my $mysql_password = 'mysql1';
-
-
my $data_source = 'DBI:mysql:' . $mysql_database_name . ':' . $mysql_server_name;
-
my $dbh = DBI->connect( $data_source, $mysql_user_name, $mysql_password, {RaiseError=>1}) || die "$DBI::errstr";
-
-
-
my $sql = $dbh->prepare(qq{SELECT * FROM samples});
-
$sql->execute();
-
-
while (my @data = $sql->fetchrow_array()) {
-
-
# Print the date from the first two columns in the table
-
print $data[0], "\t", $data[1], "<br>";
-
}
-
-
1;
-
-
# End of Database initial Query
-
#==========================================
-
-
-
-
-
my $upload_dir = 'D:/Program Files/Apache Software Foundation/Apache2.2/htdocs/upload';
-
-
# a list of valid characters that can be in filenames
-
my $filename_characters = 'a-zA-Z0-9_.-';
-
-
my $file = $query->param("photo") or error('No file selected for upload.') ;
-
my $email_address = $query->param("email") || 'Annonymous';
-
-
# get the filename and the file extension
-
# this could be used to filter out unwanted filetypes
-
# see the File::Basename documentation for details
-
my ($filename,undef,$ext) = fileparse($file,qr{\..*});
-
-
# append extension to filename
-
$filename .= $ext;
-
-
# convert spaces to underscores "_"
-
$filename =~ tr/ /_/;
-
-
# remove illegal characters
-
$filename =~ s/[^$filename_characters]//g;
-
-
# satisfy taint checking
-
if ($filename =~ /^([$filename_characters]+)$/) {
-
$filename = $1;
-
}
-
else{
-
error("The filename is not valid. Filenames can only contain these characters: $filename_characters")
-
}
-
-
# this is very crude but validating an email address is not an easy task
-
# and is beyond the scope of this article. To validate an email
-
# address properly use the Emaill::Valid module. I do not include
-
# it here because it is not a core module.
-
unless ($email_address =~ /^[\w@.-]+$/ && length $email_address < 250) {
-
error("The email address appears invalid or contains too many characters. Limit is 250 characters.")
-
}
-
-
my $upload_filehandle = $query->upload("photo");
-
-
open (UPLOADFILE, ">$upload_dir/$filename") or error($!);
-
binmode UPLOADFILE;
-
while ( <$upload_filehandle> ) {
-
print UPLOADFILE;
-
}
-
close UPLOADFILE;
-
-
my $sql = $dbh->prepare(qq{insert into samples(username, password, email_address, filename) values ( "userhello2", "passhello2", '$email_address', '$filename' ) } );
-
$sql->execute();
-
-
while (my @data = $sql->fetchrow_array()) {
-
-
# Print the date from the first four columns in the table
-
print $data[0], "\t", $data[1], "\t", $data[2], "\t", $data[3], "<br>";
-
-
}
-
-
1;
-
-
print $query->header(),
-
$query->start_html(-title=>'Upload Successful'),
-
$query->p('Thanks for uploading your photo!'),
-
$query->p("Your email address: $email_address"),
-
$query->p("Your photo $filename:"),
-
$query->img({src=>"../upload/$filename",alt=>''}),
-
$query->end_html;
-
-
-
sub error {
-
print $query->header(),
-
$query->start_html(-title=>'Error'),
-
shift,
-
$query->end_html;
-
exit(0);
-
}
-
-
|  | Expert | | Join Date: Jan 2007 Location: Southern California USA
Posts: 4,091
| | | re: perl script to query database
A problem I see in your script is using "my". The only one that will have any impact is here: - my $sql = $dbh->prepare(qq{SELECT * FROM samples});
later, and more importantly, in the same scope of the $sql variable you have: - my $sql = $dbh->prepare(qq{insert into samples(username, password, email_address, filename) values ( "userhello2", "passhello2", '$email_address', '$filename' ) } );
Any previous value $sql had is lost when you redeclare it with "my" in the same scope. So you need to remove "my" from the second line.
I don't think that is the source of the error you get because that error should be trapped by CGI::Carp and printed out to the browser.
This line is not necessary:
I don't know if it will cause a problem to include it but you can remove it and see if that helps resolve any errors. the DBI module knows where to get the driver you need in the connect string.
Remove any blank lines from the beginning of your script (before the shebang line) if there are any.
|  | Expert | | Join Date: Jan 2007 Location: Southern California USA
Posts: 4,091
| | | re: perl script to query database
Also, at line 44 of your code there is a print command. But you have not printed an HTTP header first. Since that print command is output to STDOUT it will cause the script to fail.
| | Familiar Sight | | Join Date: Sep 2008
Posts: 236
| | | re: perl script to query database
Hi Kevin / all,
Thanks Guru Kevin! I troubleshooted the script and the output is below. But the software error is there, not sure what it is, tried without or with the mysql module "use DBD::mysql;" and taken out my $sql in the insert statement. And partial html output is shown only. Code below is right after the html output. Kindly Advise... Thanks in advance.
The insert statement worked, the html PARTIALLY worked when I shift the html after the printing of the statements and the picture below. Not sure what is wrong, been circling around and still got problem.
Apache access log showed : 127.0.0.1 - - [10/Oct/2008:00:15:17 -0700] "POST /cgi-bin/u2.pl HTTP/1.1" 200 902
And perl -c u2.pl showed :
C:\Perl\bin>perl -c d:u2.pl
[Fri Oct 10 00:20:58 2008] u2.pl: "my" variable $data_source masks earlier decla
ration in same scope at d:u2.pl line 31.
[Fri Oct 10 00:20:58 2008] u2.pl: "my" variable $dbh masks earlier declaration i
n same scope at d:u2.pl line 32.
d:u2.pl syntax OK
html output(including software error below)
===============================
Thanks for uploading your photo!
Your email address: h6@email.com
Your photo E-028.JPG:
[photo is shown]
Software error:
DBD::mysql::st fetchrow_array failed: fetch() without execute() at D:/Program Files/Apache Software Foundation/Apache2.2/cgi-bin/u2.pl line 121, <fh00001D%3A\E-028.JPG> line 313.
For help, please send mail to the webmaster (admin@gateway.2wire.net), giving this error message and the time and date of the error. -
#!c:\perl\bin\perl.exe
-
#!/usr/bin/perl -T
-
use strict;
-
use warnings;
-
use CGI;
-
use CGI::Carp qw(fatalsToBrowser);
-
use File::Basename;
-
use DBD::mysql;
-
use DBI;
-
-
-
$CGI::POST_MAX = 1024 * 5000; #adjust as needed (1024 * 5000 = 5MB)
-
$CGI::DISABLE_UPLOADS = 0; #1 disables uploads, 0 enables uploads
-
-
my $query = CGI->new;
-
-
unless ($CGI::VERSION >= 2.47) {
-
error('Your version of CGI.pm is too old. You must have verison 2.47 or higher to use this script.')
-
}
-
-
-
#SECTION B
-
#=========================================
-
#Database initialization and initial query
-
my ($dbh, $data_source);
-
my $mysql_server_name = 'localhost';
-
my $mysql_database_name = 'test';
-
my $mysql_user_name = 'root';
-
my $mysql_password = 'mysql1';
-
-
my $data_source = 'DBI:mysql:' . $mysql_database_name . ':' . $mysql_server_name;
-
my $dbh = DBI->connect( $data_source, $mysql_user_name, $mysql_password, {RaiseError=>1}) || die "$DBI::errstr";
-
-
-
my $sql = $dbh->prepare(qq{SELECT * FROM samples});
-
$sql->execute();
-
-
while (my @data = $sql->fetchrow_array()) {
-
-
# Print the date from the first two columns in the table
-
print $data[0], "\t", $data[1], "<br>";
-
}
-
-
1;
-
-
# End of Database initial Query
-
#==========================================
-
-
-
-
-
my $upload_dir = 'D:/Program Files/Apache Software Foundation/Apache2.2/htdocs/upload';
-
-
# a list of valid characters that can be in filenames
-
my $filename_characters = 'a-zA-Z0-9_.-';
-
-
my $file = $query->param("photo") or error('No file selected for upload.') ;
-
my $email_address = $query->param("email") || 'Annonymous';
-
-
# get the filename and the file extension
-
# this could be used to filter out unwanted filetypes
-
# see the File::Basename documentation for details
-
my ($filename,undef,$ext) = fileparse($file,qr{\..*});
-
-
# append extension to filename
-
$filename .= $ext;
-
-
# convert spaces to underscores "_"
-
$filename =~ tr/ /_/;
-
-
# remove illegal characters
-
$filename =~ s/[^$filename_characters]//g;
-
-
# satisfy taint checking
-
if ($filename =~ /^([$filename_characters]+)$/) {
-
$filename = $1;
-
}
-
else{
-
error("The filename is not valid. Filenames can only contain these characters: $filename_characters")
-
}
-
-
# this is very crude but validating an email address is not an easy task
-
# and is beyond the scope of this article. To validate an email
-
# address properly use the Emaill::Valid module. I do not include
-
# it here because it is not a core module.
-
unless ($email_address =~ /^[\w@.-]+$/ && length $email_address < 250) {
-
error("The email address appears invalid or contains too many characters. Limit is 250 characters.")
-
}
-
-
my $upload_filehandle = $query->upload("photo");
-
-
open (UPLOADFILE, ">$upload_dir/$filename") or error($!);
-
binmode UPLOADFILE;
-
while ( <$upload_filehandle> ) {
-
print UPLOADFILE;
-
}
-
close UPLOADFILE;
-
-
-
print $query->header(),
-
$query->start_html(-title=>'Upload Successful'),
-
$query->p('Thanks for uploading your photo!'),
-
$query->p("Your email address: $email_address"),
-
$query->p("Your photo $filename:"),
-
$query->img({src=>"../upload/$filename",alt=>''}),
-
$query->end_html;
-
-
-
sub error {
-
print $query->header(),
-
$query->start_html(-title=>'Error'),
-
shift,
-
$query->end_html;
-
exit(0);
-
}
-
-
-
$sql = $dbh->prepare(qq{insert into samples(username, password, email_address, filename) values ( "userhello6", "passhello6", '$email_address', '$filename' ) } );
-
$sql->execute();
-
-
while (my @data = $sql->fetchrow_array()) {
-
-
# Print the date from the first four columns in the table
-
print $data[0], "\t", $data[1], "\t", $data[2], "\t", $data[3], "<br>";
-
-
}
-
-
-
1;
-
-
| | Familiar Sight | | Join Date: Sep 2008
Posts: 236
| | | re: perl script to query database
Hi All,
I found this, tried some methods, but still cant work well.
http://www.webmasterworld.com/forum13/3259.htm
Thanks in advance,
Andrew
Change the second statement below : -
-
$sql = $dbh->prepare(qq{insert into samples(username, password, email_address, filename) values ( "userhello66", "passhello66", '$email_address', '$filename' ) } );
-
$sql->execute() or die "$dbh->errstr\n";
-
;
-
-
while (my @data = $sql->fetchrow_array()) {
-
-
# Print the date from the first four columns in the table
-
print $data[0], "\t", $data[1], "\t", $data[2], "\t", $data[3], "<br>";
-
-
}
-
-
|  | Expert | | Join Date: Jan 2007 Location: Southern California USA
Posts: 4,091
| | | re: perl script to query database
In this line you have scalars that are single-quoted: - $sql = $dbh->prepare(qq{insert into samples(username, password, email_address, filename) values ( "userhello6", "passhello6", '$email_address', '$filename' ) } );
remove the single-quotes: - $sql = $dbh->prepare(qq{insert into samples(username, password, email_address, filename) values ( "userhello6", "passhello6", $email_address, $filename ) } );
Then retry your code. Scalars do not need to be quoted at all, and single-quotes just kills any variable interpolation anyway.
| | Familiar Sight | | Join Date: Sep 2008
Posts: 236
| | | re: perl script to query database
Hi Kevin / All,
Tried and it completely didnt work, only double quote works.. See code below. I am still get same error below when I tried to print out the data in html output although the data got inserted into the database successful., :Kindly assist.
Software error:
DBD::mysql::st fetchrow_array failed: fetch() without execute() at D:/Program Files/Apache Software Foundation/Apache2.2/cgi-bin/u2.pl line 122, <fh00001D%3A\DSC00571-resize.JPG> line 5268.
For help, please send mail to the webmaster (admin@gateway.2wire.net), giving this error message and the time and date of the error. -
-
$sql = $dbh->prepare(qq{insert into samples(username, password, email_address, filename) values ( "userhello636", "passhello636", "$email_address", "$filename") } );
-
$sql->execute() or die "$dbh->errstr\n";;
-
-
-
while (my @data = $sql->fetchrow_array()) {
-
-
# Print the date from the first four columns in the table
-
print $data[0], "\t", $data[1], "\t", $data[2], "\t", $data[3], "<br>";
-
-
}
-
-
-
1;
-
-
-
|  | Expert | | Join Date: Jan 2007 Location: Southern California USA
Posts: 4,091
| | | re: perl script to query database
Sorry, my suggestion was wrong anyway, the single-quotes were OK in the context you had them because the string is inside a qq{} operator. Its the same as this: - $foo = 'test';
-
$str = "this is a '$foo' ";
-
print $str;
So the single-quotes weren't a problem.
|  | Expert | | Join Date: Sep 2008 Location: Sydney, Australia
Posts: 173
| | | re: perl script to query database Quote:
Originally Posted by KevinADC Sorry, my suggestion was wrong anyway, the single-quotes were OK in the context you had them because the string is inside a qq{} operator. Its the same as this: - $foo = 'test';
-
$str = "this is a '$foo' ";
-
print $str;
So the single-quotes weren't a problem. hey Kevin Stop confusing me there :)
also on the topic - Software error:
-
DBD::mysql::st fetchrow_array failed: fetch() without execute() at D:/Program Files/Apache Software Foundation/Apache2.2/cgi-bin/u2.pl line 122, <fh00001D%3A\DSC00571-resize.JPG> line 5268.
its casing an error because SQL hates \ in its input, try to cancel this by \\\\ in perl
try
before you write you sql string
also watch out for single quotes ' in SQL,
| | Familiar Sight | | Join Date: Sep 2008
Posts: 236
| | | re: perl script to query database
Hi Gentlemen,
Thanks! So Which part should I try to edit? I am confused...
Thanks,
Andrew
|  | Expert | | Join Date: Sep 2008 Location: Sydney, Australia
Posts: 173
| | | re: perl script to query database Quote:
Originally Posted by happyse27 Hi Gentlemen,
Thanks! So Which part should I try to edit? I am confused...
Thanks,
Andrew
Append:
this to any place in your code where you would read, this would be after the read or this would be before you write $filename
Also
This should not work: - $sql = $dbh->prepare(qq{insert into samples(username, password, email_address, filename) values ( "userhello6", "passhello6", '$email_address', '$filename' ) } );
-
$sql->execute();
-
-
while (my @data = $sql->fetchrow_array()) {
-
-
# Print the date from the first four columns in the table
-
print $data[0], "\t", $data[1], "\t", $data[2], "\t", $data[3], "<br>";
-
-
}
Because this is an insert statement: - $sql = $dbh->prepare(qq{insert into samples(username, password, email_address, filename) values ( "userhello6", "passhello6", '$email_address', '$filename' ) } );
and this will be calling the insert statement to write and not read: - while (my @data = $sql->fetchrow_array()) {
-
-
# Print the date from the first four columns in the table
-
print $data[0], "\t", $data[1], "\t", $data[2], "\t", $data[3], "<br>";
-
this is because you have over written $sql with the write statement.
also its complaining about : fetch() without execute()
try -
-
$sql = $dbh->prepare(qq{insert into samples(username, password, email_address, filename) values ( "userhello636", "passhello636", "$email_address", "$filename") } );
-
$sql->execute() or die "$dbh->errstr\n";;
-
-
$sql = $dbh->prepare(qq{SELECT * FROM samples});
-
-
while (my @data = $sql->fetchrow_array->execute()) {
-
-
# Print the date from the first four columns in the table
-
print $data[0], "\t", $data[1], "\t", $data[2], "\t", $data[3], "<br>";
-
| | Familiar Sight | | Join Date: Sep 2008
Posts: 236
| | | re: perl script to query database
Hi Sir Icecrack,
I understand now. Thanks Again. Used your final part except one statement missing which I added... The first part not sure what you referring to. This is the code. Cheers...
Thanks,
Andrew -
#!c:\perl\bin\perl.exe
-
#!/usr/bin/perl -T
-
use strict;
-
use warnings;
-
use CGI;
-
use CGI::Carp qw(fatalsToBrowser);
-
use File::Basename;
-
use DBD::mysql;
-
use DBI;
-
-
-
$CGI::POST_MAX = 1024 * 5000; #adjust as needed (1024 * 5000 = 5MB)
-
$CGI::DISABLE_UPLOADS = 0; #1 disables uploads, 0 enables uploads
-
-
my $query = CGI->new;
-
-
unless ($CGI::VERSION >= 2.47) {
-
error('Your version of CGI.pm is too old. You must have verison 2.47 or higher to use this script.')
-
}
-
-
-
#SECTION B
-
#=========================================
-
#Database initialization and initial query
-
my ($dbh, $data_source);
-
my $mysql_server_name = 'localhost';
-
my $mysql_database_name = 'test';
-
my $mysql_user_name = 'root';
-
my $mysql_password = 'mysql1';
-
-
my $data_source = 'DBI:mysql:' . $mysql_database_name . ':' . $mysql_server_name;
-
my $dbh = DBI->connect( $data_source, $mysql_user_name, $mysql_password, {RaiseError=>1}) || die "$DBI::errstr";
-
-
-
my $sql = $dbh->prepare(qq{SELECT * FROM samples});
-
$sql->execute();
-
-
while (my @data = $sql->fetchrow_array()) {
-
-
# Print the date from the first two columns in the table
-
print $data[0], "\t", $data[1], "<br>";
-
}
-
-
1;
-
-
# End of Database initial Query
-
#==========================================
-
-
-
-
-
my $upload_dir = 'D:/Program Files/Apache Software Foundation/Apache2.2/htdocs/upload';
-
-
# a list of valid characters that can be in filenames
-
my $filename_characters = 'a-zA-Z0-9_.-';
-
-
my $file = $query->param("photo") or error('No file selected for upload.') ;
-
my $email_address = $query->param("email") || 'Annonymous';
-
-
# get the filename and the file extension
-
# this could be used to filter out unwanted filetypes
-
# see the File::Basename documentation for details
-
my ($filename,undef,$ext) = fileparse($file,qr{\..*});
-
-
# append extension to filename
-
$filename .= $ext;
-
-
# convert spaces to underscores "_"
-
$filename =~ tr/ /_/;
-
-
# remove illegal characters
-
$filename =~ s/[^$filename_characters]//g;
-
-
# satisfy taint checking
-
if ($filename =~ /^([$filename_characters]+)$/) {
-
$filename = $1;
-
}
-
else{
-
error("The filename is not valid. Filenames can only contain these characters: $filename_characters")
-
}
-
-
# this is very crude but validating an email address is not an easy task
-
# and is beyond the scope of this article. To validate an email
-
# address properly use the Emaill::Valid module. I do not include
-
# it here because it is not a core module.
-
unless ($email_address =~ /^[\w@.-]+$/ && length $email_address < 250) {
-
error("The email address appears invalid or contains too many characters. Limit is 250 characters.")
-
}
-
-
my $upload_filehandle = $query->upload("photo");
-
-
open (UPLOADFILE, ">$upload_dir/$filename") or error($!);
-
binmode UPLOADFILE;
-
while ( <$upload_filehandle> ) {
-
print UPLOADFILE;
-
}
-
close UPLOADFILE;
-
-
-
print $query->header(),
-
$query->start_html(-title=>'Upload Successful'),
-
$query->p('Thanks for uploading your photo!'),
-
$query->p("Your email address: $email_address"),
-
$query->p("Your photo $filename:"),
-
$query->img({src=>"../upload/$filename",alt=>''}),
-
$query->end_html;
-
-
-
sub error {
-
print $query->header(),
-
$query->start_html(-title=>'Error'),
-
shift,
-
$query->end_html;
-
exit(0);
-
}
-
-
-
$sql = $dbh->prepare(qq{insert into samples(username, password, email_address, filename) values ( "userhello636", "passhello636", "$email_address", "$filename") } );
-
$sql->execute() or die "$dbh->errstr\n";;
-
-
$sql = $dbh->prepare(qq{SELECT * FROM samples});
-
$sql->execute();
-
-
-
while (my @data = $sql->fetchrow_array()){
-
-
# Print the date from the first four columns in the table
-
print $data[0], "\t", $data[1], "\t", $data[2], "\t", $data[3], "<br>";
-
-
}
-
1;
-
-
|  | | | | /bytes/about
We are a network of experts and professionals in IT and software development that help one another with answers to tough questions and share insights.
Get the best answers to your questions from over 226,414 network members.
|