The Giants averted a sweep in a matchup of NL wild-card contenders. San Francisco stopped its three-game losing streak and ended the Phillies' four-game winning string.
Sanchez (9-8) became the first Giants starting pitcher to record a win in 15 games, dating to his victory over Colorado on Aug. 3. No runner reached second base against the lefty, who retired 15 straight after hitting Chase Utley with a pitch in the fourth.
Sanchez, who was vying for his first complete game since no-hitting San Diego on July 10, 2009, came out to start the ninth with a 5-0 lead. He gave up a leadoff single to Shane Victorino and was pulled with a 2-0 count on Placido Polanco.
Reliever Sergio Romo retired Polanco on a fly ball, but Utley singled and Mike Sweeney hit a two-out, two-run double. Giants manager Bruce Bochy then went to closer Brian Wilson, who got Raul Ibanez on a fly ball for 34th save in 37 opportunities.
Victorino had the Phillies' first hit, a hard single up the middle in the third.
Pablo Sandoval homered for the Giants, his ninth.
The Giants, who had scored three or fewer runs in each of their past five games, jumped on Cole Hamels (7-10) for three first-inning runs. Freddy Sanchez singled and scored on the first of Posey's doubles. The Giants rookie is 11-for-25 (.444) in his last six games.
Jose Guillen and Juan Uribe each had RBI singles later in that inning.
Hamels had received eight runs of support in his previous six starts combined, including losing consecutive 1-0 decisions. The lefty departed after giving up five runs on seven hits in five innings.
NOTES: The attendance of 45,449 was the highest for the Phillies this season, and their 100th straight sellout. ... Philadelphia's Jimmy Rollins has been safe on 29 straight stolen base attempts, the best current streak in the majors.