我正试图以JSON格式从数据库接收数据,如以下代码所示。
use strict;
use warnings;
use DBI;
use CGI;
use JSON;
my $dbh = DBI->connect('dbi:mysql:hostname=localhost:3306;database=dbname','dbuser','dbpass') or die $DBI::errstr;
$dbh->do("set names utf8");
my $sth = $dbh->prepare(qq{select NAME, ID from CUSTOMER;}) or die;
$dbh->errstr;
$sth->execute() or die $sth->errstr;
my$json={};
while(my@customer = $sth->fetchrow_array()) {
$json->{"value"} = $customer[0];
$json->{"id"} = "$customer[1]";
}
print JSON::to_json($json);
印刷输出只是一个客户:{"价值":" customer_name"," id":" 666"}。我需要得到所有客户,而不仅仅是唯一的客户。我怎么做?我的错误在哪里?
答案 0 :(得分:1)
由于你的json是一个哈希引用,你每次都要继续编写你的元素。做一些(未经测试的)
my $json=[];
while(my @customer = $sth->fetchrow_array()) {
push @{$json}, {value => $customer[0], id => $customer[1]};
}
print JSON::to_json($json);