Justin Ruggiano and Nick Green each drove in two runs for Miami in front of a season-low crowd of 13,231 at Marlins Park. Sanabia (3-6) allowed one run and seven hits over 6 1-3 innings.
Hamels (1-7) struck out 10 in six effective innings but has not won since April 28 at the New York Mets. Domonic Brown homered for the Phillies.
Miami had 11 hits and struck out 13 times on its way to scoring more than three runs for just the second time in 13 games. The Marlins have won two straight after dropping seven in a row and 10 of 11.
Sanabia and Hamels entered tied with Cubs right-hander Edwin Jackson for the NL lead in losses, but both pitched well.
Hamels, the 2008 World Series and NLCS MVP, gave up two runs and seven hits without a walk. The left-hander allowed three singles in the first inning and they resulted in a run when Marcell Ozuna drove in Adeiny Hechavarria for an early Marlins lead.
Brown homered to right in the second, his eighth of the season.
Hamels, who signed a $144 million, six-year contract last July, settled down after the first and fanned seven of 10 batters during one stretch. He gave up a leadoff single to Placido Polanco in the sixth and a two-out RBI double to Ruggiano that snapped an 0-for-18 slump and put the Marlins ahead 2-1.
Philadelphia had a pair of runners on base with one out in the seventh, but Ryan Webb relieved Sanabia and retired the next two batters to preserve the lead.
Chase Utley was caught stealing to end the eighth.
Miami tacked on three runs in the bottom half. Ruggiano had an RBI single off Phillippe Aumont to score Polanco. Two batters later, Green blooped a two-run single to shallow center that Ben Revere couldn't come up with, making it 5-1.
Chad Qualls struck out two in a hitless ninth.
NOTES: Miami placed OF Matt Diaz on the 15-day disabled list, retroactive to May 19, with a bruised left knee and selected OF Jordan Brown from Triple-A New Orleans. ... Miami rookie RHP Jose Fernandez (2-2, 3.48 ERA) will face Philadelphia for the third time on Tuesday. He has tossed 13 scoreless innings with 14 strikeouts in the first two meetings. The Phillies counter with RHP Tyler Cloyd (0-0, 2.84).