Re: fetch the column/rows and fields into hash from dbi
- From: "Pro" <peter.owen@xxxxxxxxx>
- Date: 10 Nov 2005 06:46:13 -0800
I can give you some example code that I have if that will help. I'll
try to comment on it a little more as well. Mine is from just one table
though. This is part of my "search.cgi" file that can search the
database (my one table) using several different fields.
#!/usr/bin/perl
use DBI; #use the DBI library in perl to interact with the database. In
this case MySQL
print "Content-type: text/html\n\n"; #required for the webpage to print
## Connect to the Database, if we fail, print why ##
$dbh = DBI->connect('DBI:mysql:my_db:localhost:3306', 'db_user',
'db_pass', { PrintError=>1, RaiseError => 1})
or die "Connecting: $DBI::errstr\n";
#####################
## Serial Number ##
#####################
if ($Form{scan_serial_num} != "")
{
## Search the Database only using the Serial Number (Primary Key) ##
$search = "SELECT * FROM customer_info WHERE scan_serial_num =
'$Form{scan_serial_num}'"; #This gets the value the user entered in the
form
$sth = $dbh->prepare($search);
$sth->execute; #executes the query
## If search returned information, then print each field and its value
##
## Else tell user that the search returned nothing and to retry
##
## This is the part you're interested in I think
##
if($hashref = $sth->fetchrow_hashref)
{
%rethash = %{$hashref};
if ($debug) ## if debug is not 0 then print out all of the
fields in the database
{
foreach $key (keys %rethash){print
"\$rethash{$key}=$rethash{$key}"."<BR>\n";}
}
## prints the header and body of the new page with the data in it
&retprintheader;
&retprintbody;
}
else #prints the previous page with an error on it saying to try to
search again
{
&noretprintheader;
&printnoentry;
&noretprintbody;
}
exit;
}
In other words, after you get your data back into the hash using:
if($hashref = $sth->fetchrow_hashref)
{
%rethash = %{$hashref};
Then you can specify either which key you want to get out of the hash
using $rethash{$key} where key is a field in your database such as
$owner. Or you can iterate through them using the loop I have for
debug. I hope this helps some at least.
.
- References:
- fetch the column/rows and fields into hash from dbi
- From: edwardt . tril
- fetch the column/rows and fields into hash from dbi
- Prev by Date: Re: Is it possible with RegEx
- Next by Date: Re: "system" command help
- Previous by thread: fetch the column/rows and fields into hash from dbi
- Next by thread: What is $" (can´t find it in the Camelbook)
- Index(es):
Relevant Pages
|
|