I have a query that is selecting about 20 columns, all are varchars.
Some will be empty, which is just fine. But I want to put a default string of “——-” for any columns that are empty.
Here’s what I have so far, that works:
$sql = "SELECT col1, ";
$sql .= "IF(`col2` IS NULL,'----------',`col2`) AS `col2`, ";
$sql .= "IF(`col3` IS NULL,'----------',`col3`) AS `col3`, ";
$sql .= "IF(`col4` IS NULL,'----------',`col4`) AS `col4`, ";
$sql .= "IF(`col5` IS NULL,'----------',`col5`) AS `col5`, ";
$sql .= "IF(`col6` IS NULL,'----------',`col6`) AS `col6`, ";
.......and so on.....
$sql .= "FROM `tableName`";
This works for me, but I am wondering if there’s a more “global” way, instead of specifying each column.
Following mfloryan advice you can easily generate your string with a loop and implode() function
edit. Note that information_schema is a wonderful tool to create dynamic SQL. This is an example
Regards. Nick