2013-05-31 66 views
-1

我正在使用fetchall_hashref從mysql數據庫中獲取滿足條件的數據。檢索到的數據將存儲在散列中,然後通過javascript函數使用futhur。從數據庫獲取所有數據使用fetchall_hashref

我想檢索3列的所有行並將其存儲在散列中,但無法做到這一點。

表結構..

table structure table structure

表數據..

table data table data

正在使用的代碼..

#!/usr/bin/perl -w 
#print "Content-type: text/html\n\n"; 
use DBI; 
use CGI; 
use strict; 
use warnings; 
use diagnostics; 
use Data::Dumper; 

use CGI::Carp qw (fatalsToBrowser); 
my $q = CGI->new; 
print $q->header; 
my $dsn = "DBI:mysql:Demo:localhost"; # Data source name 
my $username = "mint";     # User name 
my $password = "MINT123";    # Password 
my $dbh; 
my $sth;  
my $b; 
my $c; 
     # Database and statement handles 
$dbh = DBI->connect($dsn, $username, $password); 


my $hash = $dbh->selectall_hashref("SELECT `desc`,date1,riskval from FIR2 where date1 between date_sub(now(),INTERVAL 1 WEEK) and now() order by date1", 'riskval'); 
print Dumper($hash); 
$b=join(",",$hash); 
delete $_->{riskval} for values %$hash; 

$dbh->disconnect(); 

輸出我在瀏覽器中獲取...

browser output

膩子輸出..

enter image description here

正如你可以看到我想要打印的行,其中「riskval 「爲空,」riskval「的值是5在2個地方,但只有1行正在打印。

後,我用selectall_arrayref取代selectall_hashref我得到了以下e RROR消息中油灰..

second error message

請幫助..

+1

哈希不能有多個相同的密鑰,所以你必須使用陣列的散列或類似的東西來改變做法。 –

+0

你能舉個例子嗎? – Lucy

+0

當然,http://perldoc.perl.org/perldsc.html#Declaration-of-a-HASH-OF-ARRAYS –

回答

1

我的意思是類似於礦山的示例,其中它們的值被 從一個MySQL DB中檢索和存儲在數組中的

散列

the DBI documentation

如果$切片是一個散列引用,fetchall_arrayref取每個行作爲一個 散列引用...

例如,獲取每一行的所有字段作爲哈希REF:

$tbl_ary_ref = $sth->fetchall_arrayref({});

用這個替換你的fetchall_hashref,你應該把所有的記錄作爲一個哈希數組,包括那些重複的riskval s。

編輯:我錯過了OP使用selectall_*而不是fetchall_*。在這種情況下,DBI文檔的相關部分是:

您可能經常想要獲取一行數組,其中每行存儲爲 作爲散列。這是可以做到用簡單:

my $emps = $dbh->selectall_arrayref(
    "SELECT ename FROM emp ORDER BY ename", 
    { Slice => {} } 
); 
+0

我用「fetchall_arrayref」取代了「fetchall_hashref」,並在第二張圖片中得到了膩子中的錯誤信息...... – Lucy

+0

再次看看文檔。他們使用'selectall_arrayref'獲取哈希數組的示例是:'my $ emps = $ dbh-> selectall_arrayref( 「SELECT ename FROM emp ORDER BY ename」, {Slice => {}} );'Note唯一的參數是查詢和'{Slice => {}}'。 –

相關問題