Search → Dbi/
dbi_generic.pl
#!/usr/bin/perl -w
use strict;
use DBI;
##### PROTOTYPING
sub Debug($);
##### GLOBAL
my $DEBUG = 0; # ZZ
require "../eshop_generic.ini";
my %DATABASE = &DATABASE();
my $LANG = 'de';
my $ID = 6010;
my $G_RC = 0;
my $dbh = DBI->connect(
"dbi:Pg:dbname=$DATABASE{'db'}", $DATABASE{'user'}, $DATABASE{'pass'},
{ PrintError => 0,
AutoCommit => 1
}
) or $G_RC++;
print $DBI::errstr if $G_RC;
&main();
#########################################
sub main() {
#########################################
my @fields = qw(items.name items_attributes.attr_id items_attributes_names.name
items_attributes.val);
my $data_ref = &get_item_data(
stmt => 'SELECT ' . join(', ', @fields) .
' FROM items,items_attributes,items_attributes_names ' .
'WHERE items.id=items_attributes.item_id AND ' .
'items_attributes.attr_id=items_attributes_names.id ' .
'AND is_option=0 AND items.lang=\'' . $LANG .
"' AND items_attributes_names.lang='$LANG' AND " .
'items_attributes.lang IN (items_attributes_names.lang, \'_meta\') AND ' .
'items.id=' . $ID . ' ORDER BY attr_id' ,
fields => \@fields
);
###################################
# -- Process db records
###################################
foreach my $hash_ref (@{$data_ref->{'result_arr'}}) {
if ($DEBUG) {
Debug "$_ = \"" . $hash_ref->{$_} . '"' foreach keys %{$hash_ref}; print "\n";
}
print '- ', $hash_ref->{'items_attributes_names.name'}, ': ',
$hash_ref->{'items_attributes.val'}, "\n";
}
###################################
# -- Get a single database row
###################################
@fields = qw(has_parent);
$data_ref = &get_item_data(
stmt => 'SELECT ' . join(', ', @fields) . " FROM items WHERE id=$ID AND lang='$LANG'",
fields => \@fields
);
if (@{$data_ref->{'result_arr'}}) {
my $par_id = (\%{@{$data_ref->{'result_arr'}}[0]})->{'has_parent'};
print "par_id = $par_id\n";
}
}
#########################################
sub get_item_data(%) {
#########################################
my %args = @_;
my %hash = ();
Debug $args{'stmt'} if $DEBUG;
my $sth = $dbh->prepare($args{'stmt'}) or Debug "$DBI::errstr $args{'stmt'}";
$sth->execute() or Debug "$DBI::errstr $args{'stmt'}";
my %results = ();
$sth->bind_columns(map { \$results{$_} } @{$args{'fields'}});
my @result_arr = ();
while($sth->fetch()) {
my %p_results = %results;
push(@result_arr, \%p_results);
}
$hash{'result_arr'} = \@result_arr;
\%hash;
}
sub Debug($) { print "$_[0]\n"; }
__END__
[ Download dbi_generic.pl ]
eshop_generic.ini
# -- Save as: "eshop_generic.ini"
sub DATABASE {
(
db => 'eshop_generic',
driver => 'Pg',
user => 'apache',
pass => '',
host => 'localhost'
)
}
1;