use DBI; my $DB = DBI->connect( ... connection info goes here ...); my $sql="SELECT * FROM addressbook WHERE deprecated='0000-00-00 00:00:00' AND thumbPhoto IS NOT NULL"; my $recordset = $DB->prepare($sql); $recordset->execute(); while (my $row=$recordset->fetchrow_hashref){ open my $handle, ">", "./images/$row->{photo}"; my $data = $row->{thumPhoto}; print $handle, $row->{thumbPhoto}; }