SAN DIEGO — Denard Span singled home the go-ahead run in the sixth and Buster Posey homered an inning later for the San Francisco Giants, who held on to beat the San Diego Padres 5-4 Friday night in a matchup between two of the worst teams in baseball.

The Giants snapped a four-game losing streak and won for the second time in seven games. They remain in last place in the NL West, four games behind the fourth-place Padres.

Span’s single with two outs in the sixth gave the Giants a 4-3 lead and chased Clayton Richard (5-9). One batter earlier, pinch-hitter Miguel Gomez tied it with a sacrifice fly.

Posey homered an estimated 429 feet to straightaway center field with one out in the seventh, his 11th overall and first since June 22. The star catcher entered in a 2-for-19 slump before hitting an RBI single in the first.

Cory Gearrin (3-2) pitched one inning for the win. Sam Dyson allowed three hits and one run in the ninth but hung on for his fourth save. He gave up an RBI single to Jose Pirela and loaded the bases with two outs before getting Jabari Blash on a fly to right to end it.

Gorkys Hernandez had a career-high four hits for the Giants and scored once.

RBI singles by Posey in the first and pitcher Johnny Cueto in the second gave San Francisco a 2-0 lead. San Diego tied it in the second on Blash’s RBI double, followed by Erick Aybar’s run-scoring base hit. San Diego took the lead on Austin Hedges’ RBI single in the fourth.

Richard allowed four runs and 11 hits in 5⅔innings. He struck out four and walked two.

Cueto yielded three runs and six hits in four innings. He struck out five and walked three.

TRAINER’S ROOM

Padres: RF Hunter Renfroe was placed on the 10-day disabled list, retroactive to Monday, with a strained neck. ... RHP Kirby Yates was placed on the paternity leave list. ... To replace them, OF Blash and RHP Jose Valdez were recalled from Triple-A El Paso.