To me, the function definition should be completely outside of your program logic, it certainly shouldn't be inside a
while() loop. The physical position doesn't really matter, except that I'm always concerned that if you put it inside something like an
if() conditional and try to call it from outside that structure, it might throw an
undefined error. In any case, it makes for confusion because positioning it inside program logic suggests that it's somehow linked to that logic when, as you said, the whole point is to call it from anywhere.
So, move the function definition to the start of your PHP code, just after the
session_start() if you have one, and just call it from wherever you want to call it. Once you've got a few of these functions, and more than one PHP script to call them from, you can move just the functions out to a separate physical text file and use
require to incorporate them into each script.
While you're playing with that function, I personally wouldn't choose to have it output stuff. Right now, you're only using the function to calculate a difference and then display it, but what about later on when you have other uses, still want to calculate that difference, but don't want it displayed in the same way? Far better IMO to have the function
return the difference or an appropriate error code, and have the calling code decide how to present the results.
ETA - on that, if you were thinking that the function definition needs to be where it is so that the output appears in the correct order, that's not the case - if you move the function to the start of the file that contains your PHP, it will still give the output in the correct place because it's the program flow that dictates the order.
Thanks, though I have to admit that the only thing I was more successful at there was putting the question into Google. I've never connected to SQL server from PHP, so it's not as if I actually know what I'm talking about.