CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Beginner:
all results from single database column into an array?

 



new2perl84
Novice

Jul 10, 2009, 3:10 PM

Post #1 of 4 (377 views)
all results from single database column into an array? Can't Post

Hi All,

I have a database table with a single field, containing several rows of numerical values. For example..

data
----
100
212
345
123
111
etc...

I'd like to fetch these numbers from the database and store them into an array. So the final result would be something like @data_array which i could use elsewhere in my script.. for example using @data_array[2] to get the value 345.. and so on..

I'm familiar with using the fetchrow_array() method and a while loop to pull rows out of a table but im not sure how to make arrays out of values in the same table column.

I'd be grateful for help with this!

Thanks


ichi
User

Jul 10, 2009, 4:25 PM

Post #2 of 4 (373 views)
Re: [new2perl84] all results from single database column into an array? [In reply to] Can't Post

show your code


new2perl84
Novice

Jul 10, 2009, 4:55 PM

Post #3 of 4 (371 views)
Re: [ichi] all results from single database column into an array? [In reply to] Can't Post

sorry here is my code.. only the [0] element is being printed (the value is the first row returned from the database. But i'm not sure how to put all of the values into an array. Thanks!

#!C:/Perl/bin/perl.exe -w
#
use CGI qw(:standard);
use CGI::Carp qw(fatalsToBrowser);
use DBI;
use DBD::ODBC;
use strict;
use warnings;
print "Content-type: text/html\r\n\r\n";

my $DSN = 'driver={SQL Server};server=SERVER\INSTANCE;database=mydb;uid=user;pwd=password1;';
my $dbh = DBI->connect("dbi:ODBC:$DSN") || die "Couldn't open database: $DBI::errstr\n";

# query database

my $SQL1a = "SELECT top 100 numbers from mytable";

my $SQL1b = $dbh->prepare($SQL1a) || die "Couldn't prepare statement: $DBI::errstr\n";
$SQL1b->execute() || die "Couldn't execute statement: $DBI::errstr\n";

my @numbersarray = $SQL1b->fetchrow_array();

my $zero = $numbersarray[0];
my $first = $numbersarray[1];
my $fifty = $numbersarray[50];

print "here is array number 0: $zero <br>";
print "here is array number 1: $first <br>";
print "here is array number 50: $fifty <br>";


Crawling_key
Novice

Jul 10, 2009, 7:41 PM

Post #4 of 4 (367 views)
Re: [new2perl84] all results from single database column into an array? [In reply to] Can't Post

fetchrow will only retrieve one row. You need to put it in a loop and then assign values to the array with each iteration or use selectall_array or selectall_arrayref.

There's also a DBI subforum that you may want to look at.

 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives