Anticipate negative numbers in executable strings by wrapping in parens

This is part of the Semicolon&Sons Code Diary - consisting of lessons learned on the job. You're in the dumb-mistakes-and-gotchas category.

Last Updated: 2024-04-25

In some code to generate an SQL query for geocoding I had the following:

 <? php

 "POW((latitude-$lat)*$lat_factor,2)";

The issue was I got a negative $lat at some point, causing the SQL string to be POW((latitude--2) which is invalid.

Parentheses around the $lat variable fixed things:

 <? php

 "POW((latitude-($lat))*$lat_factor,2)";

Lesson

When building up mathematical expressions from strings (e.g. in SQL), anticipate negative numbers by wrapping any and all digits in parentheses (or spacing as necessary, etc.)