3

I'm using PHP 5.5 to retrieve a numeric value from a numeric postgresql database table field. It could come from the DB as null or as an actual number, either way I store it in a variable. As some of us may or may not know null * 1 = 0, which is something I like to do but I'm concerned about whether this is wrong or whether it is bad practice to do to convert potential null values into zeros without actually having to check the value. See below:

... $fieldVal *= 1; //assume at this point this holds value returned by DB ...

So if the db returned null then $fieldVal will be turned into zero and any non-null values will remain unchanged. Your insights are much appreciated.

atomCode
  • 842
  • 7
  • 17
  • You can use typecasting like `(int)$fieldVal`. – TheDrot Jun 07 '16 at 21:26
  • I would use the 'is_null' function in this case, but I'm not sure about the context where you are using this script, can you add a bit more of context? What function are you using to get the field value? – Tomás Cot Jun 07 '16 at 21:28
  • 1
    @TomásCot Not sure if `is_null` function exist on postgres, Is better use the ansi function `COALESCE` – Juan Carlos Oropeza Jun 07 '16 at 21:30
  • @JuanCarlosOropeza, you are right. I was thinking about doing it with PHP. But your solution is better if he is not planing on changing the db engine – Tomás Cot Jun 08 '16 at 23:24

2 Answers2

5

Change your query to include COALESCE and resolve the null cases

SELECT fieldNane

To

SELECT COALESCE(fieldName, 0)

BTW: Yes is bad practice introduce those kind of hacks.

Juan Carlos Oropeza
  • 47,252
  • 12
  • 78
  • 118
1

It really depends on who you talk to on whether your method of checking for null versus an integer is bad practice. In software development, there are a thousand ways to perform a single task, so it really is a matter of opinion.

I personally would call it bad practice, simply because PHP gives you tools to check if a variable contains null or contains an integer type. Some of those tools are functions like

is_int()

or

is_null()

And while these functions do have their own faults in a few ways, my point is, if the language has tools to perform something that you feel you are "hacking" together, use the tools provided by the language.

Geoherna
  • 3,523
  • 1
  • 24
  • 39