There are several problems with your solution - real world problems that will seriously impact the accuracy of your calculation.
The first is that this will only work if the object you are measuring is exactly parallel to the camera sensor (or you'll have perspective distortion).
The second is that focal lengths are not accurate, the number in the spec is rounded to the nearest common focal length and even that only when the lens is focused to infinity (focal length changes with focus).
And that's even before we consider distortion caused by the lens and other imperfections of real world optical devices.
Most of the problems can be solved by taking a test shot of an object with a known size